我正在使用 OpenCV 来检测下面示例图像的红色部分周围的矩形。
我的方法是使用HoughLines,然后手动找到形成矩形的4条线。矩形质量取决于内部有多少红色像素和外部有多少黑色像素。正如此处所示,此方法效果不佳(白线标记“最佳”找到的矩形)。
我对 OpenCV 或物体检测总体不太熟悉。使用其他方法来检测矩形或调整我的参数会更好吗?
读完问题后,我的理解是,你需要最小的矩形,而不是多边形,里面有所有红色像素。因此,假设是这种情况,我尝试了以下方法。在V通道上对图像进行阈值查找明亮区域,得到轮廓并得到最大轮廓的最小矩形。
请参阅下面的代码以及注释中的解释。希望这有帮助。
import cv2
import numpy as np
#Input image file path
filepath = "red_image.jpg"
image = cv2.imread(filepath)
#Csan
#gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#ret, thresholded_image = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
#Convert to HSV and get the brighness associated channel V as the TV image is brighter than others
hsv_img = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
h, s, v = hsv_img[:, :, 0], hsv_img[:, :, 1], hsv_img[:, :, 2]
#Threshold the image to get the brightest regions
ret, thresholded_image = cv2.threshold(v, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
#Find the contour of bright regions
contours, hierarchy = cv2.findContours(thresholded_image, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
#Get the largest contour, i.e. one with max area
max_area=0
max_area_ctr=None
for ctr in contours:
area = cv2.contourArea(ctr)
if area> max_area:
max_area = area
max_area_ctr = ctr
#Find the minimum rectangle that encloses the largest contour.
#This rectangle is used to draw in image.
if max_area_ctr is not None:
rect = cv2.minAreaRect(max_area_ctr)
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(image, [box], 0, (255, 255, 255), 1)
cv2.imwrite("red_image_thr.jpg",image)
cv2.imshow("Image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
else:
print("Rectangle not found.")
输出