Reputation: 21
I'm working on a small program that open an image and lets the user click on points to draw lines.
import datetime
import cv2
import numpy
clicked = False
path = "files/file1.png"
coordinates = {'x':[],'y':[]}
def onMouse(event, x, y, flags, param):
global image
global clicked
if event == cv2.EVENT_LBUTTONUP:
coordinates['x'].append(x)
coordinates['y'].append(y)
clicked = True
if (len(coordinates['x'])> 1 ):
print("debug drawing line")
cv2.line(image, (coordinates['x'][-2],coordinates['y'][-2]), (coordinates['x'][-1],coordinates['y'][-1]),(255,0,0),1)
print('debug drawing point')
cv2.circle(image,(coordinates['x'][-1],coordinates['y'][-1]), 3,(255,0,255),3)
def saveImage():
xmin, xmax = min(coordinates['x']),max(coordinates['x'])
ymin, ymax = min(coordinates['y']),max(coordinates['y'])
nombre = datetime.datetime.strftime(datetime.datetime.now(),'%Y-%m-%d-%H-%M-%S')
cv2.imwrite(f'files/Result-{nombre}.png',image[ymin:ymax,xmin:xmax])
image = cv2.imread(path)
cv2.namedWindow("Display", cv2.WINDOW_AUTOSIZE)
cv2.setMouseCallback('Display', onMouse)
active = True
while active:
cv2.imshow('Display', image)
key = cv2.waitKey(1)
if key == ord('q'):
cv2.destroyAllWindows()
active = False
if key == ord('s'):
saveImage()
cv2.destroyAllWindows()
active = False
The program opens an Image with cv2. The main loop consists of waiting for the user key input, Q to quit the program or S to save the image. When the user clicks on a point on the image, we paint a point on the image, and after the first point, we paint lines between the points.
I'm trying to add a codeblock to reset the image like this
if key == ord('r'):
resetImage()
def resetImage():
print('Debug: reset Image')
coordinates['x'].clear()
coordinates['y'].clear()
# image = cv2.imread(path)
# cv2.destroyAllWindows()
This has a result but obviously it's not what I'm looking for.
Upvotes: -4
Views: 97
Reputation: 21
The issue was that I was trying to access a global variable the wrong way. I solved it like this:
def resetImage():
global image
print("Debug: reset Image")
coordinates["x"].clear()
coordinates["y"].clear()
newImage = cv2.imread(path)
image = newImage.copy()
Upvotes: 0