python - 在 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()
解决方案
你可以这样做:
#!/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()
推荐阅读
- python - 你可以在 python 中尽可能长地迭代一个列表吗?
- matplotlib - 如何使用 pyplot 绘制类似网格的图像?
- command-line - 在命令参数中使用环境变量代替文件
- python - 替换 , 为 . 在熊猫数据框中进行类型转换之前
- java - 创建类层次结构时,构成层次结构的类的构造函数按什么顺序调用?
- javascript - api调用者可以访问res.locals吗?
- wordpress - 我想在 wordpress 的后期编辑屏幕上维护保存在类别或自定义分类术语选择上的顺序
- sql - 在 SQL 中声明表时出现语法错误
- react-native - 单击输入时反应本机如何获取输入
- r - Zelen 精确测试 - 尝试在函数 zelen.test() 中使用 ak 2x2