Go directly to the code, there is nothing to say
import math
import cv2 as cv
import numpy as np
tangle = [0, 0, 0, 0]
start = [0, 0]
click = False
change='l'
def draw(path):
global change
cv.namedWindow('1', 0)
cv.resizeWindow('1', 600, 600)
cv.setMouseCallback('1', call_back)
while cv.waitKey(1) != 27:
# Esc
img = cv.imread(path)
pt1 = (tangle[0], tangle[1])
pt2 = (tangle[2], tangle[3])
center=[int((tangle[0] + tangle[2]) / 2), int((tangle[1] + tangle[3]) / 2)]
# 求圆的中心点
r=(tangle[2]-tangle[0])**2+(tangle[3]-tangle[1])**2
# 求圆的半径
radius=int(math.sqrt(r)/2)
if change=='l':
# change='l',画直线
cv.line(img, pt1, pt2, (255, 0, 0), 2)
cv.imshow('1', img)
elif change=='r':
# change='r',画圆
cv.circle(img,center,radius,(255,0,0),2)
cv.imshow('1', img)
# change='t',画矩形
elif change=='t':
cv.rectangle(img, pt1, pt2, (255, 0, 0), 2)
cv.imshow('1', img)
# 回调函数
def call_back(event, x, y, flags, param):
global click,change
# 按下左键
if event == cv.EVENT_LBUTTONDOWN:
start[0] = x
start[1] = y
click = True
# 移动
if event == cv.EVENT_MOUSEMOVE:
if click:
tangle[0] = start[0]
tangle[1] = start[1]
tangle[2] = x
tangle[3] = y
# 释放
if event == cv.EVENT_LBUTTONUP:
left_palce = (tangle[0], tangle[1])
right_palce = (tangle[2], tangle[3])
click = False
# 左击两次,从键盘输入,改变change
if event==cv.EVENT_LBUTTONDBLCLK:
key=cv.waitKey(0)
if key==ord('l'):
change='l'
elif key==ord('r'):
change='r'
elif key==ord('t'):
change='t'
operate
draw('1.jpg')
# 运行函数
starting time
The default is to draw lines (parameters and the like can be set by yourself)
Double-click the left button and press r on the keyboard. At this time, the double-click event is called, change='r', at this time
When I draw a picture again, I draw a circle, which is dynamic.
In the same way, double-click and press t to draw a rectangle
Summarize
There are also irregular shapes drawn every time.
If you draw a rectangle on the picture, you can use selectROI to cut it out. What if it is a circle or an irregular picture?
Cut?