-1

I am trying to draw and crop rotated rectangle into opencv python but I don't know how to do it. I have x,y coordinates width and height of rectangle and searched about how to find contours of that x,y coordinates for using cv2.minAreaRect() but can't make it.

I am giving line coordinates and also drawn a line on it to show you.where I want to draw rectangle of height 2 and width same as line. Line Coordinates: x1, y1, x2, y2 = 542, 771, 1757, 977

image with line where I want to draw and crop rectangle

I can not explain it properly please understand what I want.

I tried it with following script but I don't know how to find contours from x, coordinates

import cv2
import numpy as np


def main():
    img = cv2.imread("/home/infinity/Pictures/1.png")
    # points for test.jpg
    cnt = np.array([
            [[64, 49]],
            [[122, 11]],
            [[391, 326]],
            [[308, 373]]
        ])
    print("shape of cnt: {}".format(cnt.shape))
    rect = cv2.minAreaRect(cnt)
    print("rect: {}".format(rect))

    # the order of the box points: bottom left, top left, top right,
    # bottom right
    box = cv2.boxPoints(rect)
    box = np.int0(box)

    print("bounding box: {}".format(box))
    cv2.drawContours(img, [box], 0, (0, 0, 255), 2)

    # get width and height of the detected rectangle
    width = int(rect[1][0])
    height = int(rect[1][1])

    src_pts = box.astype("float32")
    # corrdinate of the points in box points after the rectangle has been
    # straightened
    dst_pts = np.array([[0, height-1],
                        [0, 0],
                        [width-1, 0],
                        [width-1, height-1]], dtype="float32")

    # the perspective transformation matrix
    M = cv2.getPerspectiveTransform(src_pts, dst_pts)

    # directly warp the rotated rectangle to get the straightened rectangle
    warped = cv2.warpPerspective(img, M, (width, height))

    # cv2.imwrite("crop_img.jpg", warped)
    cv2.waitKey(0)


if __name__ == "__main__":
    main()

1 Answers1

0

It appears to be basically duplicate question to Draw rectangle in OpenCV. It obviously contains a definition of rectangle for OpenCV.

If you're having acutally trouble to get coordinates, then we need to know what is the goal. If the camera has static view, then it would be obviusly trivial, just using an editor like Gimp to read them. I sense it might be a moving camera or some other complication stand in a way...

If you meant something different, you should really express what do you want to achieve.

Oak_3260548
  • 1,882
  • 3
  • 23
  • 41