Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

code #3010

Open
zhongyihebao opened this issue Dec 18, 2023 · 0 comments
Open

code #3010

zhongyihebao opened this issue Dec 18, 2023 · 0 comments

Comments

@zhongyihebao
Copy link

zhongyihebao commented Dec 18, 2023

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()

test_image1
test_image2
test_image3
test_image4
test_image5
test_image6
test_image7
test_image8
test_image9
我所期望的到的效果图是这样的
aim

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant