import os
import cv2
import numpy as np
from math import atan2, degrees
from random import sample
def process_image(image_path):
image = cv2.imread(image_path)
image = cv2.resize(image, (600, 600))
# 高斯模糊和二值化
gs_frame = cv2.GaussianBlur(image, (11, 11), 0)
gray = cv2.cvtColor(gs_frame, cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(gray, 145, 255, cv2.THRESH_BINARY_INV)
# 寻找轮廓
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 筛选有效轮廓
valid_contours = [cnt for cnt in contours if cv2.arcLength(cnt, True) > 400 and cv2.contourArea(cnt) > 20000]
# 初始化状态和最佳轮廓
status = "需要直行"
# 绘制最佳轮廓的拟合线
if best_contour is not None:
[vx, vy, x, y] = cv2.fitLine(best_contour, cv2.DIST_L2, 0, 0.01, 0.01)
vx, vy, x, y = vx[0], vy[0], x[0], y[0]
lefty = int((-x * vy / vx) + y)
righty = int(((binary.shape[1] - x) * vy / vx) + y)
cv2.line(image, (int(binary.shape[1]), righty), (0, lefty), 255, 2)
# 绘制所有有效轮廓的矩形框
for contour in valid_contours:
x, y, w, h = cv2.boundingRect(contour)
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2) # 绿色矩形框
print(f"图片'{os.path.basename(image_path)}'所示情况{status}。")
可以加Q 3562487425交流