Life2Coding
How to Crop OpenCV Image using Mouse Click and Movement in Python

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

Code:

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[0][1]:refPoint[1][1], refPoint[0][0]:refPoint[1][0]]
            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()

Output:

 

crop How to Crop OpenCV Image using Mouse Click and Movement in Python

life2coding_icon [] How to Crop OpenCV Image using Mouse Click and Movement in Python

2 thoughts on “How to Crop OpenCV Image using Mouse Click and Movement in Python

  1. mikael

    Thank you for this code. I have a question how can send the coordinates of the selected region to a file and save the crop image. I am a beginner in programming.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.