简体   繁体   中英

Python opencv: draw a circle on a image, when a key is pressed

I want to press a letter in the keyboard to draw a circle, but the circle is only draw when the mouse is moving.

import cv2
import numpy as np

mode = True
ix, iy = -1, -1


def draw_circle(event, x, y, flags, param):
    global ix, iy, mode


if cv2.waitKey(1) == ord('r'):
    cv2.circle(img, (x, y), 18, (255, 0, 0), -1)

img = np.zeros((512, 512, 3), np.uint8)
cv2.namedWindow('image')
cv2.setMouseCallback('image', draw_circle)

while 1:
    cv2.imshow('image', img)
    k = cv2.waitKey(1) & 0xFF
    if k == ord('m'):
        mode = not mode
    elif k == 27:
        break
        
cv2.destroyAllWindows()

You have a several mistakes, first. Draw circle is set as a mouse callback. When the mouse moves, clicks, etc. it calls that function. If your aim is to create a circle where the mouse is currently positioned, you can change the mouse callback to only record the position of the mouse every time it moves or clicks. And then, when you check if you hit m call draw circle to this position. Also, I would recommend 10 ms wait, if not it may not get the key pressed (it has happen to me) so you have to hit it several times. I have not tested this code, but it is probably correct :) I hope it helps you.

import cv2
import numpy as np

ix,iy = -1,-1
def set_mouse_position(event,x,y,flags,param):
    global ix,iy
    ix,iy = x,y 

img = np.zeros((512,512,3), np.uint8)
cv2.namedWindow('image')
cv2.setMouseCallback('image',set_mouse_position)

while(1):
    cv2.imshow('image',img)
    k = cv2.waitKey(10) & 0xFF
    if k == ord('m'):
        cv2.circle(img,(ix,iy),18,(0,0,0),-1)
    elif k == 27:
        break
cv2.destroyAllWindows()

Try:

cv2.circle(img,(ix,iy),18,(255,0,0),-1)

Also press 'm' key

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