为了账号安全,请及时绑定邮箱和手机立即绑定

如何在图像中找到矩形轮廓?

如何在图像中找到矩形轮廓?

HUX布斯 2021-08-05 10:15:32
我目前正在从事一个从卫星图像中识别足球场的项目。这是一个足球场的顶视图卫星图像我使用了 mediumblur 功能清除了这张图片中的所有小杂质。后来我只选择了图像的绿色部分,并使用命令 cv2.inRange(hsv_img, light_green, dark_green) 制作了一个蒙版,其中 light_green 和 dark_green 是我在 hsv 中的绿色范围。拿到口罩后。我得到了这个作为输出:由于它有一些杂质,我使用了 mediumblur 函数中值 = cv2.medianBlur(image, 45) 我得到的输出是:正如你所看到的,我有很多轮廓和中间的主要矩形轮廓。我需要一种从图像中选择这种矩形轮廓的算法,而我必须忽略其余部分。这之后我该怎么办?
查看完整描述

2 回答

?
守着一只汪

TA贡献1872条经验 获得超3个赞

我的方法是:

  1. 从输入图像中找到“正方形”或“矩形”之类的形状

  2. 找到最大面积的那个。

假设输入是您计算的“中值”结果:

//img1.sycdn.imooc.com//610b4a0b0001d52906570371.jpg

中值图像(输入):


首先,导入必要的库并净化镜像。


import cv2

import numpy as np

# assuming you have the result image store in median

# median = cv2.imread("abc.jpg", 0)

image_gray = median 

image_gray = np.where(image_gray > 30, 255, image_gray)

image_gray = np.where(image_gray <= 30, 0, image_gray)

image_gray = cv2.adaptiveThreshold(image_gray, 255,

                           cv2.ADAPTIVE_THRESH_GAUSSIAN_C,

                           cv2.THRESH_BINARY, 115, 1)

找到轮廓,然后根据它们的形状应用过滤功能。


_, contours, _ = cv2.findContours(image_gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

rect_cnts = []

for cnt in contours:

    peri = cv2.arcLength(cnt, True)

    approx = cv2.approxPolyDP(cnt, 0.04 * peri, True)

    (x, y, w, h) = cv2.boundingRect(cnt)

    ar = w / float(h)

    if len(approx) == 4: # shape filtering condition

        rect_cnts.append(cnt)

找出面积最大的那个,并画出结果。


max_area = 0

football_square = None

for cnt in rect_cnts:

    (x, y, w, h) = cv2.boundingRect(cnt)

    if max_area < w*h:

        max_area = w*h

        football_square = cnt


# Draw the result

image = cv2.cvtColor(image_gray, cv2.COLOR_GRAY2RGB)

cv2.drawContours(image, [football_square], -1, (0, 0,255), 5)

cv2.imshow("Result Preview", image)

cv2.waitKey()

结果预览:

//img1.sycdn.imooc.com//610b4a1b0001d41f06540368.jpg

查看完整回答
反对 回复 2021-08-05
  • 2 回答
  • 0 关注
  • 198 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号