import cv2
image =cv2.imread(r'2900_10_mask.jpg', 1)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
binary = cv2.adaptiveThreshold(~gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 15, -5)
cv2.imshow("binary", binary) # 展示图片
contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
src_copy = image.copy()
max_area=0
max_point=None
for contour in contours:
x, y, w, h = cv2.boundingRect(contour) # 计算点集最外面的矩形边界
if w*h>max_area:
max_area=w*h
max_point=(x,y,x+w,y+h)
cv2.rectangle(src_copy, (max_point[0], max_point[1]), (max_point[2], max_point[3]), (0, 255, 0), 2)
cv2.imshow("one", src_copy) # 展示图片
retval, binary = cv2.threshold(gray, 15, 255, cv2.THRESH_BINARY)
cv2.imshow("binary2", binary) # 展示图片
contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
src_copy = image.copy()
max_area=0
max_point=None
for contour in contours:
x, y, w, h = cv2.boundingRect(contour) # 计算点集最外面的矩形边界
if w*h>max_area:
max_area=w*h
max_point=(x,y,x+w,y+h)
cv2.rectangle(src_copy, (max_point[0], max_point[1]), (max_point[2], max_point[3]), (0, 255, 0), 2)
cv2.imshow("result", src_copy) # 展示图片
cv2.waitKey()
python opencv 二值化提取掩码矩形框
最新推荐文章于 2024-05-29 13:01:06 发布