0

If I use cv2.imshow to create three windows and make focus on one of them, I want to get this window's name in order to save this image. How to do this?

I find nothing about this question, maybe someone can tell me how to ask more precisely?

cv2.imshow("pic1",src)
cv2.imshow("pic2",hsv)
cv2.imshow("pic3",gray)
if cv2.waitKey(0) == ord('s'):
    cv2.imwrite("./src.png",src)

In this code, I want to save what the focus on others rather than src.

HansHirse
  • 18,010
  • 10
  • 38
  • 67
buenos
  • 42
  • 6
  • Save the image using `imwrite` – T A Nov 27 '19 at 10:38
  • Related: [Obtain Active window using Python - Stack Overflow](https://stackoverflow.com/questions/10266281/obtain-active-window-using-python) although may be overkill. – user202729 Jun 03 '23 at 03:05

1 Answers1

2

The only solution I could come up with solely using OpenCV's High-level GUI functions, would be to set up a mouse callback with custom parameters representing the window's name and content, i.e. the image. Then, for example catching the left mouse button down event sets some global variables accordingly to the window's parameters. Finally, in some infinite loop, key presses are recorded, and when the s key is pressed, the image from the current chosen window is saved using the proper name.

Please see the following code:

import cv2


# Set up mouse callback
def update_for_save(event, x, y, flags, params):
    global image, window_name

    # On left mouse button down (i.e. when the focus goes to the window), update global variables
    if event == cv2.EVENT_LBUTTONDOWN:
        image = params[1]
        window_name = params[0]


# Images
src = cv2.imread('path/to/some/image.png')
hsv = cv2.cvtColor(src, cv2.COLOR_BGR2HSV)
gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)

# Window params
image = None
window_name = None

# Create windows, add mouse callbacks
cv2.imshow('pic1', src)
cv2.imshow('pic2', hsv)
cv2.imshow('pic3', gray)
cv2.setMouseCallback('pic1', update_for_save, ['pic1', src])
cv2.setMouseCallback('pic2', update_for_save, ['pic2', hsv])
cv2.setMouseCallback('pic3', update_for_save, ['pic3', gray])

while True:
    key = cv2.waitKey(1) & 0xFF

    # If s key is pressed, save image specified by global variables
    if key == ord('s'):
        cv2.imwrite(window_name + '.png', image)

    # If q key is pressed, close all windows
    elif key == ord('q'):
        cv2.destroyAllWindows()

Hope that helps!

HansHirse
  • 18,010
  • 10
  • 38
  • 67