How to put rectangle mask onto rectangular-ish object

I want to put placeholder objects for further analysis into rectangular objects.

I found code to mark corners of rectangles, but my objects' corners are not "sharp" enough.

import cv2
import numpy as np

img = cv2.imread('image.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = np.float32(gray)

corners = cv2.goodFeaturesToTrack(gray, 100, 0.01, 60)
corners = np.int0(corners)

for corner in corners:
    x, y = corner.ravel()
    cv2.circle(img, (x,y), 3, 255, -1)

cv2.imwrite('Corners.png', img)

enter image description here enter image description here

The corners are not detected properly.

  1. Is there a way to achieve this?
  2. How would I put a (perfect) rectangle into the object, so that it serves as placeholder?

I want something like this:

enter image description here

Upvotes: 0

Views: 515

Answers (1)

Nuzhny
Nuzhny

Reputation: 1927

  1. Find all contours.
  2. For each contour find a bounding rotated rectangle:

    rect = cv2.minAreaRect(cnt)

    box = cv2.cv.BoxPoints(rect)

  3. Decrease width and height of the rotated rectangle until (sum of pixels into rect == width * height)

Upvotes: 1

Related Questions