[Solved] How draw bounding box on Specfic Area using Opencv python? [closed]


Here is my Python/OpenCV code. I can get the region by a judicious choice of area thresholding. But this is not likely going to be robust for other images.

Input:

enter image description here

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)

Threshold image:

enter image description here

Bounding box:

enter image description here

6

solved How draw bounding box on Specfic Area using Opencv python? [closed]