2 回答

TA贡献1872条经验 获得超3个赞
我的方法是:
从输入图像中找到“正方形”或“矩形”之类的形状
找到最大面积的那个。
假设输入是您计算的“中值”结果:
中值图像(输入):
首先,导入必要的库并净化镜像。
import cv2
import numpy as np
# assuming you have the result image store in median
# median = cv2.imread("abc.jpg", 0)
image_gray = median
image_gray = np.where(image_gray > 30, 255, image_gray)
image_gray = np.where(image_gray <= 30, 0, image_gray)
image_gray = cv2.adaptiveThreshold(image_gray, 255,
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY, 115, 1)
找到轮廓,然后根据它们的形状应用过滤功能。
_, contours, _ = cv2.findContours(image_gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
rect_cnts = []
for cnt in contours:
peri = cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, 0.04 * peri, True)
(x, y, w, h) = cv2.boundingRect(cnt)
ar = w / float(h)
if len(approx) == 4: # shape filtering condition
rect_cnts.append(cnt)
找出面积最大的那个,并画出结果。
max_area = 0
football_square = None
for cnt in rect_cnts:
(x, y, w, h) = cv2.boundingRect(cnt)
if max_area < w*h:
max_area = w*h
football_square = cnt
# Draw the result
image = cv2.cvtColor(image_gray, cv2.COLOR_GRAY2RGB)
cv2.drawContours(image, [football_square], -1, (0, 0,255), 5)
cv2.imshow("Result Preview", image)
cv2.waitKey()
结果预览:
添加回答
举报