Click and Crop Image
You can easily crop an image using mouse clicks on OpenCV. For this you need call the OpenCV cv2.setMouseCallback(“window”, image). You then need to detect the left mouse button down using the cv2.EVENT_LBUTTONDOWN event, then continuously locate the position of the mouse using the cv2.EVENT_MOUSEMOVE event and at last you need to detect the left mouse button released or cv2.EVENT_LBUTTONUP event.
By doing this it will create an rectangle to the image and also give the output ROI of the cropped image
import cv2 import numpy as np cropping = False x_start, y_start, x_end, y_end = 0, 0, 0, 0 image = cv2.imread('test.jpg') oriImage = image.copy() def mouse_crop(event, x, y, flags, param): # grab references to the global variables global x_start, y_start, x_end, y_end, cropping # if the left mouse button was DOWN, start RECORDING # (x, y) coordinates and indicate that cropping is being if event == cv2.EVENT_LBUTTONDOWN: x_start, y_start, x_end, y_end = x, y, x, y cropping = True # Mouse is Moving elif event == cv2.EVENT_MOUSEMOVE: if cropping == True: x_end, y_end = x, y # if the left mouse button was released elif event == cv2.EVENT_LBUTTONUP: # record the ending (x, y) coordinates x_end, y_end = x, y cropping = False # cropping is finished refPoint = [(x_start, y_start), (x_end, y_end)] if len(refPoint) == 2: #when two points were found roi = oriImage[refPoint:refPoint, refPoint:refPoint] cv2.imshow("Cropped", roi) cv2.namedWindow("image") cv2.setMouseCallback("image", mouse_crop) while True: i = image.copy() if not cropping: cv2.imshow("image", image) elif cropping: cv2.rectangle(i, (x_start, y_start), (x_end, y_end), (255, 0, 0), 2) cv2.imshow("image", i) cv2.waitKey(1) # close all open windows cv2.destroyAllWindows()
- How to Draw Arrow Lines in OpenCV Python - 20 October, 2021
- How to Add Logo or Image Watermark on Images with OpenCV Python - 19 October, 2021
- How to Add Text Watermark on Images with OpenCV Python - 18 October, 2021