1 import cv2
2 import numpy as np
3 import matplotlib.pyplot as plt
4
5 # 读取图像并转换为灰度图像
6 image = cv2.imread('./a.jpg')
7 gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
8
9 # 使用 Canny 边缘检测
10 edges = cv2.Canny(gray, 0, 200) # 调整阈值参数
11
12 # 寻找轮廓
13 contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
14
15 # 过滤出长宽大于150的轮廓
16 filtered_contours = [contour for contour in contours if cv2.boundingRect(contour)[2] > 110 and cv2.boundingRect(contour)[3] > 110]
17
18 # 对轮廓按面积进行排序
19 sorted_contours = sorted(filtered_contours, key=cv2.contourArea, reverse=True)[:10] # 只保留最大的五个轮廓
20
21 # 绘制矩形轮廓
22 for contour in sorted_contours:
23 x, y, w, h = cv2.boundingRect(contour)
24 cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
25
26 # 创建一个与原始图像相同大小的空白图像
27 mask = np.zeros_like(image)
28
29 # 将轮廓内的区域更改为背景颜色
30 for contour in sorted_contours:
31 x, y, w, h = cv2.boundingRect(contour)
32 cv2.rectangle(mask, (x, y), (x + w, y + h), (255, 255, 255), thickness=cv2.FILLED)
33
34
35 # 将填充区域与原始图像进行叠加
36 result = np.where(mask != 255, image, mask)
37 # result = cv2.bitwise_and(image, cv2.bitwise_not(mask))
38 # 显示结果
39 plt.imshow(result[:,:,::-1])