Save two gbr value in OpenCV-Python

Question:

Everything works correctly in the code, but I want the code to save two values and then end. How can I do that?

import cv2
import numpy as np

def mouse(event,x,y,flags,param):
    if event == cv2.EVENT_LBUTTONDOWN: 
        colorsb = image[y,x,0]
        colorsg = image[y,x,1]
        colorsr = image[y,x,2]
        colors = image[y,x]
        
        print("Red: ",colorsr)
        print("Green: ",colorsg)
        print("Blue: ",colorsb)
        print("BRG : ",colors)
        print("Coordinates of pixel: X: ",x,"Y: ",y)

image = cv2.imread("x.jpg")
cv2.namedWindow("Image")
cv2.setMouseCallback("Image", mouse)

while(1):
    cv2.imshow("Image",image)
    if cv2.waitKey(1) & 0xFF == 27:
        break

cv2.destroyAllWindows()

My Image:

My Image

Asked By: Lynoix

||

Answers:

You could do something like this:

#!/usr/bin/env python3

import cv2
import numpy as np

def mouse(event,x,y,flags,param):
    # Ensure we change global "done" rather than a local copy
    global done
    if event == cv2.EVENT_LBUTTONDOWN: 
        colorsb = image[y,x,0]
        colorsg = image[y,x,1]
        colorsr = image[y,x,2]
        colors = image[y,x]
        
        print("Red: ",colorsr)
        print("Green: ",colorsg)
        print("Blue: ",colorsb)
        print("BRG : ",colors)
        print("Coordinates of pixel: X: ",x,"Y: ",y)

        # Write results to file
        with open('result.txt', 'w') as f:
           f.write(f'Coords: [{x},{y}], BRG: {colors}')

        # Signal main loop to exit
        done = True

image = cv2.imread("MNFnp.jpg")
cv2.namedWindow("Image")
cv2.setMouseCallback("Image", mouse)

done = False
while not done:
    cv2.imshow("Image",image)
    if cv2.waitKey(1) & 0xFF == 27:
        break

cv2.destroyAllWindows()
Answered By: Mark Setchell
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.