Mask_RCNN
Mask_RCNN copied to clipboard
code
import cv2 import numpy as np import matplotlib.pyplot as plt
def detect_and_mark_rectangles(image): # 降噪 denoised_image = cv2.GaussianBlur(image, (5, 5), -10)
# 将图像转换为灰度
gray_image = cv2.cvtColor(denoised_image, cv2.COLOR_BGR2GRAY)
# 进行二值化处理
_, binary_image = cv2.threshold(gray_image, 122, 255, cv2.THRESH_BINARY)
# 执行 Canny 边缘检测
edges = cv2.Canny(binary_image, 10, 255)
# 找到洞的轮廓
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 找到最大的绿色边界
max_area = 0
max_contour = None
for contour in contours:
# 计算轮廓的近似多边形
epsilon = 0.02 * cv2.arcLength(contour, True)
approx = cv2.approxPolyDP(contour, epsilon, True)
# 如果近似多边形是矩形,则进行标注
if len(approx) == 4:
area = cv2.contourArea(contour)
if area > max_area:
max_area = area
max_contour = approx
# 绘制最大的绿色内边界
if max_contour is not None:
cv2.drawContours(image, [max_contour], 0, (0, 255, 0), 2)
# 寻找外边界
outer_contours, _ = cv2.findContours(binary_image, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
outer_contours = [cnt for cnt in outer_contours if cv2.contourArea(cnt) > max_area]
# 绘制红色外边界
cv2.drawContours(image, outer_contours, -1, (0, 0, 255), 2)
return image
读取和处理多张图片
image_paths = ['test_image{}.jpg'.format(i) for i in range(1, 10)]
for path in image_paths: # 读取图像 image = cv2.imread(path)
# 进行矩形检测和标注
result = detect_and_mark_rectangles(image)
# 使用Matplotlib显示结果图像
plt.imshow(cv2.cvtColor(result, cv2.COLOR_BGR2RGB))
plt.axis('off')
plt.title('Result')
plt.show()
我所期望的到的效果图是这样的