【发布时间】:2022-11-18 04:09:18
【问题描述】:
我正在尝试开发一种根据显示器颜色更改 RGB LED 灯条的设备。为此,我计划截取屏幕并标准化/取显示器中各个像素颜色的平均值。我在标准化图像和取出图像的平均颜色时遇到问题。这是我正在使用的代码。
import numpy as np
import cv2
import mss
import time
def getAverageColor(frame):
(B, G, R) = 0, 0, 0
for i in frame:
for j in i:
B += j[0]
G += j[1]
R += j[2]
B /= len(frame) * len(frame[0])
G /= len(frame) * len(frame[0])
R /= len(frame) * len(frame[0])
return (B, G, R)
with mss.mss() as sct:
# Grab frames in an endless lopp until q key is pressed
time.sleep(2)
# Itterate the list of monitors, and grab one frame from each monitor (ignore index 0)
for monitor_number, mon in enumerate(sct.monitors[1:]):
monitor = {"top": mon["top"], "left": mon["left"], "width": mon["width"], "height": mon["height"], "mon": monitor_number} # Not used in the example
# Grab the data
img = np.array(sct.grab(mon)) # BGRA Image (the format BGRA, at leat in Wiqndows 10).
print(getAverageColor(img))
# Show down-scaled image for testing
# The window name is img0, img1... applying different monitors.
cv2.imshow(f'img{monitor_number}', cv2.resize(img, (img.shape[1]//4, img.shape[0]//4)))
key = cv2.waitKey(1)
if key == ord('q'):
break
cv2.destroyAllWindows()
该程序运行良好,但我想问一下是否有任何方法可以去除 openCV 本身的平均颜色,因为我的方法不是很好推荐,因为它的处理速度可能非常慢。不要添加这个,但代码也不是很准确。
【问题讨论】:
-
作为 getAverageColor 的想法:
return cv.cvtColor(frame, cv.COLOR_BGR2HSV)[0].mean()?这是更短的,试试看是否更快。要设置 LED,您不关心亮度,对吗?总是 100%? -
让我试一试并在最终代码上更新此线程。
标签: python python-3.x opencv image-processing