如何保存由某个轨迹栏修改的图像?

2024-09-26 22:54:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试保存由轨迹栏修改的图像。当我尝试保存它(使用imwrite)时,它只保存在轨迹栏修改之前的图像。下面的代码中没有显示,但我尝试在foo函数中使用imwrite,但没有成功。我还尝试从foo函数返回图像和getTrackbarPos,但这两个值都是未修改的输入

import cv2


def foo(val):
    thresholdVal = cv2.getTrackbarPos('trackbar','window')
    _, dst = cv2.threshold(image, thresholdVal, 255, cv2.THRESH_BINARY)
    cv2.imshow('window',dst)


image = cv2.imread('img.jpg')

cv2.namedWindow('window')

cv2.createTrackbar('trackbar','window',0,255,foo)

foo(0)

cv2.waitKey(0)
cv2.destroyAllWindows

Tags: 函数代码图像imageimportfoo轨迹def
1条回答
网友
1楼 · 发布于 2024-09-26 22:54:14

只需在脚本录制结束时添加一个无限循环。例如,按s时,保存当前dst图像。您需要另一个键作为退出循环的指示器,例如使用q。然后foo方法中的dst映像需要是全局的,以便后面的无限循环可以访问

下面是一些代码:

import cv2


def foo(val):

    # Destination image and threshold value must be global
    global dst, thresholdVal

    thresholdVal = cv2.getTrackbarPos('trackbar', 'window')
    _, dst = cv2.threshold(image, thresholdVal, 255, cv2.THRESH_BINARY)
    cv2.imshow('window', dst)


image = cv2.imread('path/to/your/image.png')
dst = image.copy()

cv2.namedWindow('window')
cv2.createTrackbar('trackbar', 'window', 0, 255, foo)

thresholdVal = 0
foo(thresholdVal)

# Add infinite loop, tracking key presses
# on hitting 's' key -> save the image with the current threshold value
# on hitting 'q' key -> quit, and terminate program
# Attention: Do NOT close the window by pressing the 'x' button!
while True:

    k = cv2.waitKey(1) & 0xFF

    if k == ord('s'):
        cv2.imwrite('image_' + str(thresholdVal) + '.png', dst)
        print('Saved image as image_' + str(thresholdVal) + '.png')

    if k == ord('q'):
        break

cv2.destroyAllWindows()

thresholdVal变量在这里也需要是全局变量,因为我在图像文件名中使用它的值

                    
System information
                    
Platform:      Windows-10-10.0.16299-SP0
Python:        3.8.5
OpenCV:        4.5.1
                    

相关问题 更多 >

    热门问题