import cv2 as cv import numpy as np points = [] def click_event(event, x, y, flags, param): global points, img_copy if event == cv.EVENT_LBUTTONDOWN: points.append((x, y)) cv.circle(img_copy, (x, y), 5, (0, 0, 255), -1) cv.imshow("Image", img_copy) if len(points) == 4: for i in range(4): cv.line(img_copy, points[i], points[(i+1) % 4], (0, 255, 0), 2) cv.imshow("Image", img_copy) crop_box() def crop_box(): global points, img src_pts = np.array(points, dtype="float32") width = int(max(np.linalg.norm(src_pts[0] - src_pts[1]), np.linalg.norm(src_pts[2] - src_pts[3]))) height = int(max(np.linalg.norm(src_pts[1] - src_pts[2]), np.linalg.norm(src_pts[3] - src_pts[0]))) dst_pts = np.array([ [0, 0], [width - 1, 0], [width - 1, height - 1], [0, height - 1] ], dtype="float32") M = cv.getPerspectiveTransform(src_pts, dst_pts) cropped_img = cv.warpPerspective(img, M, (width, height)) cv.imshow("Cropped Image", cropped_img) cv.imwrite("cropped_image.png", cropped_img) cv.waitKey(0) cv.destroyAllWindows() img_path = "/Users/vlacosmi/Documents/Personal/detect_picture/detect-flying-kitties-main/video-frames/frame_0953.png" img = cv.imread(img_path) img_copy = img.copy() cv.imshow("Image", img_copy) cv.setMouseCallback("Image", click_event) cv.waitKey(0) cv.destroyAllWindows()