本文基于图像颜色,主要结合RGB和HSI两种判断依据进行火焰识别。
判断依据参考了以下文章,实在是非常感谢!:
OpenCV学习记录之视频中的火焰检测识别
python版基于颜色的火焰识别
判断条件如下:
- R>redThre
- R>=G>=B
- S>0
- S>(255-R)/20
- S>=((255-R)*sThre/redThre)
具体代码实现:
img = cv2.imread('fire/fire4.jpeg')
redThre = 115 # 115~135红色分量阈值
sThre = 60 # 55~65饱和度阈值
B = img[:, :, 0]
G = img[:, :, 1]
R = img[:, :, 2]
B1 = img[:, :, 0] / 255
G1 = img[:, :, 1] / 255
R1 = img[:, :, 2] / 255
minValue = np.array(
np.where(R1 <= G1, np.where(G1 <= B1, R1, np.where(R1 <= B1, R1, B1)), np.where(G1 <= B1, G1, B1)))
sumValue = R1 + G1 + B1
# HSI中S分量计算公式
S = np.array(np.where(sumValue != 0, (1 - 3.0 * minValue / sumValue), 0))
Sdet = (255 - R) / 20
SThre = ((255 - R) * sThre / redThre)
#判断条件
fireImg = np.array(
np.where(R > redThre, np.where(R >= G, np.where(G >= B, np.where(S > 0, np.where(S > Sdet, np.where(
S >= SThre, 255, 0), 0), 0), 0), 0), 0))
gray_fireImg = np.zeros([fireImg.shape[0], fireImg.shape[1], 1], np.uint8)
gray_fireImg[:, :, 0] = fireImg
meBImg = cv2.medianBlur(gray_fireImg, 5)
kernel = np.ones((5, 5), np.uint8)
ProcImg = cv2.dilate(meBImg, kernel)
#绘制矩形框
contours, _ = cv2.findContours(ProcImg, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
ResImg = img.copy()
for c in range(0, len(contours)):
# 获取矩形的左上角坐标(x,y),以及矩形的宽和高w、h
x, y, w, h = cv2.boundingRect(contours[c])
l_top = (x, y)
r_bottom = (x + w, y + h)
cv2.rectangle(ResImg, l_top, r_bottom, (255, 0, 0), 2)
cv2.imshow("RESULT", ResImg)
c = cv2.waitKey(0)
输出结果如下:
基于颜色的火焰识别,如果图片中除了火焰还有一些橘色、红色等颜色相近的地方,识别效果就会差很多,例如下面,手指也识别出来了。
针对这个问题,目前我没有找到合适的解决方法,所以接下来准备通过机器学习的方式进行火焰识别(ง •̀_•́)ง