目标:将红色的部分滤出,转化为绿色
下面是代码+ 效果 + 解释
import cv2 import numpy as np def dectfun(frame): # convert the frame to hsv color space hsv = cv2.cvtcolor(frame, cv2.color_bgr2hsv) # define the range for red color in hsv lower_red1 = np.array([0, 120, 70]) upper_red1 = np.array([10, 255, 255]) lower_red2 = np.array([170, 120, 70]) upper_red2 = np.array([180, 255, 255]) # create a mask for red color mask1 = cv2.inrange(hsv, lower_red1, upper_red1) mask2 = cv2.inrange(hsv, lower_red2, upper_red2) mask = mask1 + mask2 # create an output image to show the detected red regions in green result = frame.copy() result[mask > 0] = [0, 255, 0] # change red regions to green return result def main(): # open the webcam cap = cv2.videocapture(1) while true: # read a frame ret, frame = cap.read() if not ret: break # detect red regions and highlight them result = dectfun(frame) # display the result cv2.imshow("frame", result) if cv2.waitkey(1) & 0xff == ord('q'): break # release the webcam and close all windows cap.release() cv2.destroyallwindows() if __name__ == "__main__": main()
转hsv: 关于颜色总是要转hsv的
hsv = cv2.cvtcolor(frame, cv2.color_bgr2hsv)
掩膜
lower_red1 = np.array([0, 120, 70]) upper_red1 = np.array([10, 255, 255]) lower_red2 = np.array([170, 120, 70]) upper_red2 = np.array([180, 255, 255]) # create a mask for red color mask1 = cv2.inrange(hsv, lower_red1, upper_red1) mask2 = cv2.inrange(hsv, lower_red2, upper_red2) mask = mask1 + mask2
在这段代码中,mask 是一个数组。具体来说,它是一个二值图像(即一个包含0和255的数组),表示在hsv颜色空间中红色区域的掩膜。 在掩膜区域内的是我们的目标lower_red1, upper_red1
标注是255 其余是0
再标注
# create an output image to show the detected red regions in green result = frame.copy() result[mask > 0] = [0, 255, 0] # change red regions to green return result
result = frame.copy()
在python中,变量通常是引用类型,如果你在函数中直接修改传入的数组或对象,它们的值会永久改变。result[mask > 0] = [0, 255, 0]
这是个巧妙的句子,当mask的对应位置上的值大于零。 然后把result 对应位置上的像素改成绿色
总结
到此这篇关于python+opencv处理颜色之将目标颜色转换的文章就介绍到这了,更多相关python opencv目标颜色转换内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论