【发布时间】:2020-06-06 02:35:39
【问题描述】:
我的图像是 ndarray(2048, 2048, 3)。我想修改它并保留以前版本的副本(大约 5 个),这样我就可以撤销通过点击事件完成的任何修改。
在下面的代码中,我为每次点击图像绘制圆圈。但是,我想存储多个图像并在每次右键单击时删除最后一张 (pop())。
click_pts = []
def click(event, x, y, flags, param):
global click_pts, image, image_ref
if event == cv2.EVENT_LBUTTONDOWN:
click_pts.append((x, y))
image_ref = np.ndarray.copy(image)
cv2.circle(image, (x, y), 5, (255, 0, 0), -1)
cv2.imshow("image", image)
print((x, y))
elif event == cv2.EVENT_RBUTTONDOWN:
click_pts.pop()
image = np.ndarray.copy(image_ref)
cv2.imshow("image", image)
image = cv2.imread('images/RT1_2th.png')
image_ref = np.ndarray.copy(image)
cv2.namedWindow("image")
cv2.setMouseCallback("image", click)
# Loop until 'q' is pressed
while True:
cv2.imshow("image", image)
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
cv2.destroyAllWindows()
我没有找到任何可靠的方法来将多个图像存储在一个数组中......不管它是什么类型的数组,但是拥有.pop() 函数会很棒。
另外,(旁注),在OpenCV example 中,image 没有传递到函数中,并且单击会导致(如果我从click 中删除global image):
UnboundLocalError: local variable 'image' referenced before assignment
我不太喜欢全局变量,我想知道,有什么替代方案? 编辑: 添加了两个函数来处理移位。 lshift 向左移动并用新的图像替换最后一个图像:
def lshift(arr, new_arr):
result = np.empty_like(arr)
result[:-1] = arr[1:]
result[-1] = new_arr
return result
def rshift(arr):
result = np.empty_like(arr)
result[1:] = arr[:-1]
result[0] = arr[0]
return result
它工作得很好,但不要忘记使用np.array.copy() 传递所绘制图像的值。否则,它会通过引用传递,而您最终会得到所有内容的相同副本!
【问题讨论】:
标签: python python-3.x opencv numpy-ndarray