1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| import cv2 import numpy as np
img = cv2.imread('lingbosize.png') gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) ret,thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV| cv2.THRESH_OTSU)
contours,hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) mask = np.zeros(img.shape,np.uint8)#原图大小的纯黑图 draw = np.zeros(img.shape,np.uint8)#将原图copy 到 draw上,加上mask操作 temp = np.zeros(img.shape,np.uint8)#每次循环,重置mask 和 draw i = 0
for contour in contours: area = cv2.contourArea(contour) print(f"AREA:{area}") B = 255 G = 255 R = 255 mask = temp.copy() draw = temp.copy() if(area > 300): cv2.drawContours(mask,contour,-1,(B,G,R),cv2.FILLED)#cv2.FILLED填充轮廓内 ROIname = 'ROI{}'.format(i) ROI = cv2.bitwise_and(img,mask) cv2.imshow(ROIname,ROI) i+=1 cv2.waitKey(0) cv2.destroyAllWindows()
|