Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to save the image modified by the trackbar. When I try to save it (using imwrite), it only saves the image before it has been modified by the trackbar. Not shown in the following code, but I have tried using imwrite in the foo function which did not work. I also tried returning the image and the getTrackbarPos from the foo function, but both values were the unmodified inputs.

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
question from:https://stackoverflow.com/questions/65907325/how-to-save-an-image-modified-by-some-trackbar

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
426 views
Welcome To Ask or Share your Answers For Others

1 Answer

Simply add an infinite loop at the end of your script recording key presses. For example, when pressing s, save the current dst image. You'll need another key as an indicator to quit the loop, for example use q. The dst image from your foo method then needs to be global to be accessible by the later infinite loop.

Here's some code:

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()

The thresholdVal variable just needs to be global here, too, because I use its value in the image filename.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...