如何从函数内部分配给全局变量?如何使用 CV2 重置绘制的图像?

问题描述 投票:0回答:1

我正在开发一个小程序,可以打开图像并让用户单击点来绘制线条。

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

程序打开一个带有cv2的图像。主循环包括等待用户按键输入、Q 退出程序或 S 保存图像。当用户单击图像上的一个点时,我们在图像上绘制一个点,在第一个点之后,我们在点之间绘制线条。

我正在尝试添加一个代码块来重置图像,如下所示

if key == ord('r'):
        resetImage()
def resetImage():
    print('Debug: reset Image')
    coordinates['x'].clear()
    coordinates['y'].clear()
    # image = cv2.imread(path)   
    # cv2.destroyAllWindows()

这有结果,但显然这不是我想要的。

python opencv computer-vision global-variables
1个回答
0
投票

问题是我试图以错误的方式访问全局变量。我是这样解决的:

def resetImage():
global image
print("Debug: reset Image")
coordinates["x"].clear()
coordinates["y"].clear()
newImage = cv2.imread(path)
image = newImage.copy()
© www.soinside.com 2019 - 2024. All rights reserved.