crazybin98
crazybin98

Reputation: 19

How to do image processing inside box created by cv2.minAreaRect only?

I draw a rotated rectangle in the original image. Is it possible to do image processing in the rotated rectangle box only without cropping it out from the original image? enter image description here enter image description here

original = cv2.imread(r'image.jpg')

ori_img = original.copy()
img = cv2.cvtColor(ori_img, cv2.COLOR_BGR2GRAY)
img = cv2.GaussianBlur(img,(5,5),0)
_, thresh = cv2.threshold(img, 130, 255, cv2.THRESH_BINARY_INV)
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

for cnt in contours:
    [x, y, w, h] = cv2.boundingRect(cnt)
    if (w*h) >= 10000:
        box = cv2.minAreaRect(np.asarray(cnt))
        pts = cv2.boxPoints(box)
        pts = np.int0(pts)
cv2.drawContours(ori_img, [pts], 0, (0,255,0), 3)    
cv2.namedWindow('Frame', cv2.WINDOW_NORMAL)
cv2.imshow('Frame',ori_img)
k = cv2.waitKey(0)

Upvotes: 0

Views: 669

Answers (1)

Christoph Rackwitz
Christoph Rackwitz

Reputation: 15403

Short answer: no.

No OpenCV functions take a RotatedRect to limit the area they are working on.

Long answer: maybe.

Some OpenCV functions can take a mask argument. Many don't.

To calculate a mask from the rotated rectangle, use boxPoints and then draw a filled polygon with color 255 into an array of dtype uint8 and shape (height, width)

mask = np.zeros((height, width), dtype=np.uint8)

# pts from boxPoints is a float32 array, fillPoly only likes integers
cv.fillPoly(
    img=mask,
    pts=np.round(pts).astype(np.int32).reshape((-1, 1, 2)), # round, cast, reshape into 2-channel column vector
    color=255)

Longer answer: do your operations, then copy back using the mask.

source = ...
altered = your_operations(source)
source[mask != 0] = altered[mask != 0]

To reduce the amount of work, you can do your operations on a subregion too (and then use mask to copy back).

Upvotes: 2

Related Questions