首页 > 解决方案 > 在 OpenCV-Python 中保存两个 gbr 值

问题描述

代码中一切正常,但我希望代码保存两个值然后结束。我怎样才能做到这一点?

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

我的形象

标签: pythonfunctionnumpyopencv

解决方案


你可以这样做:

#!/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()

推荐阅读