如何使用 Opencv python 在特定区域绘制边界框?

How draw bounding box on Specfic Area using Opencv python?

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

这是我的 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)

阈值图像:

边界框: