如何在Python中删除图像上的绘制线条?

时间:2015-11-05 15:11:12

标签: python opencv

我在python中使用opencv包绘制了几行(使用opencv包),在现有图像的顶部点击鼠标(每次鼠标点击都是连接点),您可以将其视为允许用户在图像上选择某些内容。

如何通过单击鼠标右键来允许用户删除图像上的最后一个点?这是我目前的代码:

import numpy
import cv2

points = []

def draw_point(event, x, y, flags, param):
    if event == cv2.EVENT_LBUTTONDOWN:
        cv2.circle(image, (x,y), 1, (255,0,0),-1)
        points.append((x,y))
        pts = numpy.array(points, numpy.int32)
        cv2.polylines(image,[pts],False,(255,0,0))
    elif event == cv2.EVENT_RBUTTONDOWN:
        # HOW TO DELETE?
        del points[-1]
        pts = numpy.array(points, numpy.int32)
        cv2.polylines(image,[pts],True,(255,0,0))



image = cv2.imread('simple_tattoo.jpg', cv2.IMREAD_UNCHANGED)

cv2.namedWindow('example', cv2.WINDOW_AUTOSIZE)
cv2.setMouseCallback('example', draw_point)


while(1):
   cv2.imshow('example',image)

   if cv2.waitKey(20) & 0xFF == 27:
        break

cv2.destroyAllWindows()

print (points)

是否有更简单的方法在图像上绘制线条(任何东西)?

2 个答案:

答案 0 :(得分:2)

每次操作后都保留图像的缓存,然后在需要时简单地返回到缓存状态。就像撤消

def draw_circle(event,x,y,flags,param):
    global img
    global cache
    if event == cv2.EVENT_LBUTTONDBLCLK:
        cache = copy.deepcopy(img)
        cv2.circle(img,(x,y),40,(255,0,0),5)

    if event == cv2.EVENT_MBUTTONDBLCLK:
        img = copy.deepcopy(cache)
        cv2.imshow('image', img)

img_path = "my_img.jpg"        
global img  
global cache      
img = cv2.imread(img_path)  
cache = copy.deepcopy(img)
cv2.namedWindow('image')  

while(1):
    cv2.setMouseCallback('image', draw_circle)
    cv2.imshow('image', img)
    k=cv2.waitKey(1) & 0xFF
    if k==27: #Escape KEY
        break

    cv2.imshow('image', img)

cv2.destroyAllWindows()

答案 1 :(得分:0)

因此,如果其他人遇到此问题,同样重要的是还要保持一阵子循环以刷新img-没有它就无法工作

def click_event(event, x, y, flags, param):
    global img 
    if event == cv2.EVENT_LBUTTONDOWN:
        print(x,y)
        cv2.circle(img, (x, y), 10, (0, 0, 255), -1)
        cv2.imshow('image', img)
    if event == cv2.EVENT_RBUTTONDBLCLK:
        img = cv2.imread(img_path)
        print("cleaned")
        cv2.imshow('image', img)

img_path = "my_img.jpg"        
global img        
img = cv2.imread(img_path)        

while(1):
    cv2.setMouseCallback('image', click_event)
    cv2.imshow('image', img)
    k=cv2.waitKey(1) & 0xFF
    if k==27: #Escape KEY
        break

    cv2.imshow('image', img)

cv2.destroyAllWindows()