月夜钓钱江鱼

醉后不知天在水,满船清梦压星河。
posts - 50,comments - 8,views - 29026

 

复制代码
 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()
复制代码

 

posted on   湘灵  阅读(28)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

点击右上角即可分享
微信分享提示