简体   繁体   中英

Implement mouse input with opencv on an image

I found some code online and I changed it a little. I am doing a navigation project and want user to input a start and end point by clicking on the map image. Here is what I have:

import cv2 as cv2

def draw_circle(event,x,y,flags,param):
    global mouseX,mouseY
    if event == cv2.EVENT_LBUTTONDBLCLK:
        cv2.circle(img,(x,y),2,(0,0,0),-1)
        mouseX,mouseY = x,y

img = cv2.imread("1.png")
img = cv2.resize(g1,(800,600))
cv2.namedWindow('image')
cv2.setMouseCallback('image',draw_circle)
cv2.imshow('image',img)

Normally we need a cv2.waitKey() for this image to be shown, but in this case, I really don't know what to do next.

I want to show this map view, and when user double-click on it, it will show a black dot(this is implemented). After user input two points, the image will close and the function will return two sets of pixel wise coordinate indicate where did the user click.

I saw people putting cv2.imshow() and cv2.waitKey() in a while loop, this will show the image and the click function is working fine as well. But I don't know how to return the pixel coordinate in that way.

import cv2 as cv2

def draw_circle(event,x,y,flags,param):
    global mouseX,mouseY
    if event == cv2.EVENT_LBUTTONDBLCLK:
        cv2.circle(img,(x,y),2,(0,0,0),-1)
        mouseX,mouseY = x,y
        cv2.destroyWindow('image')
        print('last position: ', mouseX, mouseY)

img = cv2.imread("1.jpg")
img = cv2.resize(img, (800,600))
cv2.namedWindow('image')
cv2.setMouseCallback('image',draw_circle)
cv2.imshow('image',img)
cv2.waitKey()

If you run, this code, it will register the last position the mouse, destory the window and print the result the console. The trick you, should use the x and y provided by the callback funtion. Hope this helps.

import cv2 import numpy as np def mouse_callback(event, x, y, flags, param): if event == cv2.EVENT_LBUTTONDOWN: global mouseX, mouseY, last_mouseX, last_mouseY last_mouseX, last_mouseY = mouseX, mouseY mouseX, mouseY = x, y print("x =", mouseX, "\ty =", mouseY) print("last_x =", last_mouseX, "last_y =", last_mouseY) global disp_img disp_img = np.copy(img) cv2.circle(disp_img, (mouseX,mouseY), 2, (0,0,255), -1) cv2.circle(disp_img, (last_mouseX,last_mouseY), 2, (255,0,0), -1) mouseX, mouseY, last_mouseX, last_mouseY = 0, 0, 0, 0 img = cv2.imread('ip.jpg') disp_img = np.copy(img) winname = 'image' cv2.namedWindow(winname) cv2.setMouseCallback(winname, mouse_callback) # we need to loop imshow in order to draw the circle ch = 0 while ch != 27: # press esc to exit cv2.imshow('image', disp_img) ch = cv2.waitKey(1) cv2.destroyAllWindows()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM