1 import cv2 2 import numpy as np 3 4 org = cv2.imread('cards.png') 5 6 imgray = cv2.cvtColor(org, cv2.COLOR_BGR2GRAY) 7 cv2.imshow('imgray', imgray) 8 9 # 白色背景 10 ret, threshold = cv2.threshold(imgray, 244, 255, cv2.THRESH_BINARY_INV) # 把黑白颜色反转 11 cv2.imshow('after threshold', threshold) 12 13 contours, hierarchy = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) 14 15 areas = list() 16 for i, cnt in enumerate(contours): 17 areas.append((i, cv2.contourArea(cnt)))#面积大小 18 19 #按面积大小,从大到小排序 20 a2 = sorted(areas, key=lambda d: d[1], reverse=True) 21 22 cv2.waitKey(10)#要先按一下键盘 23 for i, are in a2: 24 if are < 150: 25 continue 26 img22 = org.copy()#逐个contour 显示 27 cv2.drawContours(img22, contours, i, (0, 0, 255), 3) 28 print(i, are) 29 30 cv2.imshow('drawContours', img22) 31 k = cv2.waitKey(200) 32 if k == ord('q'): 33 break 34 35 # 获取最大或某个contour,剪切 36 idx = a2[1][0] 37 mask = np.zeros_like(org) # Create mask where white is what we want, black otherwise 38 cv2.drawContours(mask, contours, idx, (0, 255, 0), -1) # Draw filled contour in mask 39 out = np.zeros_like(org) # Extract out the object and place into output image 40 out[mask == 255] = org[mask == 255] 41 cv2.imshow('out_contour.jpg', out) 42 43 # roi方法 44 idx = a2[4][0] 45 x, y, w, h = cv2.boundingRect(contours[idx]) 46 roi = org[y:y + h, x:x + w] 47 cv2.imshow('out_contour-roi4.jpg', roi) 48 cv2.waitKey(0) 49 cv2.destroyAllWindows()