Import the image and convert the grayscale, select the perceptual area to extract the grayscale value

This time is a small project, which needs to import the opencv library, just simply judge which position of the traffic light is on

import cv2 as cv

# 导入图片,并转为灰度图
img = cv.imread("hong.png", 0)
# 保存到硬盘
cv.imwrite('giay.jpg', img)

 

 This is the effect after grayscale conversion

The sensitive area I chose is the light position of the traffic lights, which are three pictures.

# (584,163) h : 31   w :33 计算出感性区域的像素值
# img[y:y+h,x:x+w]
imgRoI_R = img[425:472, 580:618]
cv.imshow("ROI", imgRoI_R)
cv.waitKey()
# 第二张
imgRoI_Y = img[425:472, 620:653]
cv.imshow("ROI", imgRoI_Y)
cv.waitKey()
# 第三张
imgRoI_G = img[425:472, 652:690]
cv.imshow("ROI", imgRoI_G)
cv.waitKey()

Finally, the gray value of each image is extracted, traversed, and compared with a selected flag value. If the corresponding value is larger, the light will be on. Here I am a red light.

# 设变量
lum = 0
a = 0
sum = 0
# 遍历第一张感性区域的像素值,得出灰度值的均值
for x in range(47):
    for y in range(38):
        lum = lum + imgRoI_R[x][y]
        a = a + 1
sum = lum / a

# 设变量
# 遍历第二张感性区域的像素值,得出灰度值的均值
lum2 = 0
a2 = 0
sum2 = 0
for x in range(47):
    for y in range(33):
        lum2 = lum2 + imgRoI_Y[x][y]
        a2 = a2 + 1
sum2 = lum2 / a2

# 设变量
# 遍历第三张感性区域的像素值,得出灰度值的均值
lum3 = 0
a3 = 0
sum3 = 0
for x in range(47):
    for y in range(38):
        lum3 = lum3 + imgRoI_G[x][y]
        a3 = a3 + 1
sum3 = lum3 / a3

# 以一个数为标准,灰度值大于这个数,即亮。
standard = 40
if sum > standard:
    print("红灯亮")
if sum2 > standard:
    print("黄灯亮")
if sum3 > standard:
    print("绿灯亮")

Guess you like

Origin blog.csdn.net/weixin_65996583/article/details/126879548