opencv矩形检测python_如何用python 3,opencv 3对矩形进行等高线检测?
你的方法有一些小缺陷,下面的代码将有所帮助。
代码:import numpy as np
import cv2
image = cv2.imread('C:/Users/Jackson/Desktop/score.jpg')
#--- Resized the image to half its dimension maintaining the aspect ratio ---
image = cv2.resize(image, (0, 0), fx = 0.5, fy = 0.5)
draw = np.zeros_like(image)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#--- I found the inverse binary image, because contours are found for objects in white. Since the border of the page is in black you have to invert the binary image. This is where it went wrong.
ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV|cv2.THRESH_OTSU)
#--- I did not perform any morphological operation ---
im, cnts, hier = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
max_area = -1
max_c = 0
for i in range(len(cnts)):
contour = cnts[i]
area = cv2.contourArea(contour)
if (area > max_area):
max_area = area
max_c = i
contour = cnts[max_c]
rect = cv2.minAreaRect(contour)
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(image, [box],-1, (0, 255, 0), 2)
cv2.imshow('Sheet', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
结果:

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)