Life2Coding
How to Paint on OpenCV Images and Save Image

This application is written in Python 3.6 and it utilizes the exceptionally celebrated OpenCV library. OpenCV is a computer vision and machine learning programming library that incorporates numerous basic picture examination calculations that will enable us to manufacture custom, intelligent computer vision applications. You can check more on here: OpenCV Python

You can now easily paint on OpenCV images. For this you need to call the setMouseCallback(‘window_name’,image_name) function on opencv. After that you can easily handle the Mouse Callback Function upon your images. Then you need to detect the cv2.EVENT_LBUTTONDOWN, cv2.EVENT_MOUSEMOVE and cv2.EVENT_LBUTTONUP events. By checking the proper boolean condition you need to decide how you like to interact with the OpenCV images.

Code:

import cv2
import numpy as np

drawing=False # true if mouse is pressed
mode=True

# mouse callback function
def paint_draw(event,former_x,former_y,flags,param):
    global current_former_x,current_former_y,drawing, mode

    if event==cv2.EVENT_LBUTTONDOWN:
        drawing=True
        current_former_x,current_former_y=former_x,former_y

    elif event==cv2.EVENT_MOUSEMOVE:
        if drawing==True:
            if mode==True:
                cv2.line(image,(current_former_x,current_former_y),(former_x,former_y),(0,0,255),5)
                current_former_x = former_x
                current_former_y = former_y
    elif event==cv2.EVENT_LBUTTONUP:
        drawing=False
        if mode==True:
            cv2.line(image,(current_former_x,current_former_y),(former_x,former_y),(0,0,255),5)
            current_former_x = former_x
            current_former_y = former_y
    return former_x,former_y


image = cv2.imread("hanif.jpg")
cv2.namedWindow("OpenCV Paint Brush")
cv2.setMouseCallback('OpenCV Paint Brush',paint_draw)
while(1):
    cv2.imshow('OpenCV Paint Brush',image)
    k=cv2.waitKey(1)& 0xFF
    if k==27: #Escape KEY
        cv2.imwrite("painted_image.jpg",image)
        break
cv2.destroyAllWindows()

Output:

2 How to Paint on OpenCV Images and Save Image 1 How to Paint on OpenCV Images and Save Image

 

life2coding_icon [] How to Paint on OpenCV Images and Save Image

One thought on “How to Paint on OpenCV Images and Save Image

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.