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()
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix