【问题标题】:How draw bounding box on Specfic Area using Opencv python? [closed]如何使用 Opencv python 在特定区域绘制边界框? [关闭]
【发布时间】:2021-09-27 09:31:51
【问题描述】:

我想知道如何使用 OpenCV python 在特定区域绘制边界框,如下图所示?

【问题讨论】:

  • 找到最暗区域的阈值。与形态的清洁。然后得到轮廓。然后得到边界框。
  • 我是 python 新手,我被困在这个问题上,你能分享一下吗
  • 发布一张没有蓝色矩形的原始图片。
  • 我已经发布了原图请检查
  • 我试过了。但是左右的暗区混淆了这个过程,我不能只区分中心区域。对不起。

标签: python python-3.x image opencv image-processing


【解决方案1】:

这是我的 Python/OpenCV 代码。我可以通过明智地选择区域阈值来获得该区域。但这对于其他图像来说不太可能是稳健的。

输入:

import cv2
import numpy as np

# read image
img = cv2.imread("younas.jpg")

# convert img to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# median filter
gray = cv2.medianBlur(gray, 9)

# threshold
thresh = cv2.threshold(gray, 50, 255, cv2.THRESH_BINARY)[1]

# invert
thresh_inv = 255 - thresh

# get contours
contours = cv2.findContours(thresh_inv , cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]

# filter on area and draw rectangle biased to compensate for median blur
result = img.copy()
for cntr in contours:
    area = cv2.contourArea(cntr)
    if area > 1000 and area < 3000:
        x,y,w,h = cv2.boundingRect(cntr)
        cv2.rectangle(result, (x-9, y-9), (x+w+9, y+h+9), (0, 0, 255), 2)

# write results
cv2.imwrite("younas_threshold.jpg", thresh)
cv2.imwrite("younas_result.jpg", result)

# display results
cv2.imshow("thresh", thresh)
cv2.imshow("result", result)
cv2.waitKey(0)

阈值图像:

边界框:

【讨论】:

  • 如何设置区域(1000,3000)?
  • 我快速测量了尺寸(手动)。这就是为什么我说我不认为解决方案会很强大。
  • 是的,它不能很好地工作,那么如何使它健壮/?
  • 我不知道任何可靠的方法。我不想发帖,因为它不够健壮。但你坚持要我告诉你我做了什么。
  • @ Hammad Younas 既然我不厌其烦地按照您的要求发布代码,请您至少给我的回答一个简单的赞成票。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-15
  • 1970-01-01
  • 2021-11-26
  • 2021-12-03
  • 2021-10-09
  • 1970-01-01
  • 2013-01-08
相关资源
最近更新 更多