OpenCV通过红色和绿色过滤图像

时间:2020-08-01 09:12:06

标签: python opencv image-processing computer-vision

我想将下面的图像过滤为绿色和红色。过滤图像的目的是能够计算图像中的红色和绿色单元。我正在使用OpenCV过滤图像,但结果与预期不符,请以红色和绿色过滤器查看图像。过滤后的图像似乎包含更多两种颜色的像元,这将导致计数错误。我可以在代码中做些什么来改善这一点?非常感谢。

import cv2

image = cv2.imread('2020-03-Sequence-p4-Day-0_Position070.png')

b = image.copy()
# set green and red channels to 0
b[:, :, 1] = 0
b[:, :, 2] = 0


g = image.copy()
# set blue and red channels to 0
g[:, :, 0] = 0
g[:, :, 2] = 0

r = image.copy()
# set blue and green channels to 0
r[:, :, 0] = 0
r[:, :, 1] = 0


# RGB - Blue
cv2.imshow('B-RGB', b)

# RGB - Green
cv2.imshow('G-RGB', g)

# RGB - Red
cv2.imshow('R-RGB', r)

cv2.waitKey(0)

原始enter image description here图片 convert_images enter image description here

1 个答案:

答案 0 :(得分:1)

您的意思是这样的吗?

import cv2
import numpy as np

## Read
img = cv2.imread("img.jpg")

## convert to hsv
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

mask_green = cv2.inRange(hsv, (36, 25, 25), (70, 255,255))
mask_red1 = cv2.inRange(hsv, (0, 70, 50), (10, 255, 255))
mask_red2 = cv2.inRange(hsv, (170, 70, 50), (180, 255, 255))
mask_orange = cv2.inRange(hsv, (10, 100, 20), (25, 255, 255))
mask_yellow = cv2.inRange(hsv, (21, 39, 64), (40, 255, 255))

## slice the red and orange
imask_red1 = mask_red1>0
imask_red2 = mask_red2>0
imask_orange = mask_orange>0
imask_yellow = mask_yellow>0
red = np.zeros_like(img, np.uint8)
red[imask_red1] = img[imask_red1]
red[imask_red2] = img[imask_red2]
red[imask_orange] = img[imask_orange]
red[imask_yellow] = img[imask_yellow]

## slice the green
imask_green = mask_green>0
green = np.zeros_like(img, np.uint8)
green[imask_green] = img[imask_green]

## save 
cv2.imwrite("green.jpg", green)
cv2.imwrite("red.jpg", red)

enter image description here enter image description here

有些绿色变成了红色版本,我想您可以调整hsv范围以解决此问题