python cv realize binarization detection region

Function: detecting a maximum rectangular region in the image

Code:

import cv2
import numpy as np

imgpath = './test1.jpeg'
img = cv2.imread(imgpath)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
(_, thresh) = cv2.threshold(gray, 160, 255, cv2.THRESH_BINARY)
(_, cnts, _) = cv2.findContours(thresh.copy(),cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

areas = [cv2.contourArea(c) for c in cnts]
max_index = np.argmax(areas)
cnt = cnts[max_index]
x,y,w,h = cv2.boundingRect(cnt)

cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
cv2.imshow("show",img)
cv2.imwrite("./test1_rect.jpg", img)
cv2.waitKey()

effect:

Guess you like

Origin blog.csdn.net/weixin_41770169/article/details/93516463