简体   繁体   中英

How could I filter an image by using a single RGB color?

I am new to the Python world, also to programming. I have to do the following task: I have to take a screenshot on my PC, showing a specific area in Google Maps Traffic Mode.

Traffic info is shown by 4 colors. These colors are Green, Orange, Red, and a darker Red. Through simple programs I can check what the specific colors are. I mean exact values, eg B: 150, G:100, R:75 .

How I can isolate (keep) this color and make all other pixels white. I have already tried using HSV masking, but I didn't have very good results. I also tried with trackbar and HSV, results are the same. I most commonly use OpenCV, matplotlib, numpy...etc. I underline that I would like if possible a solution with rgb, something like loop through all pixels and keep only those with the specific color. Thank you!

Colors we need:

orange      R:255, G:151, B:77
green       R:99,  G:214, B:104
red         R:242, G:60,  B:50
Dark red    R:129, G:31,  B:31

EXAMPLE

import cv2
import numpy as np
image = cv2.imread('08.00am.Monday.png')
cv2.namedWindow('image', cv2.WINDOW_NORMAL)
lower = np.array([2, 100, 100])
upper = np.array([75, 255, 255])
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, lower, upper)
output = cv2.bitwise_and(image,image, mask= mask)
cv2.imshow('image',output)
cv2.waitKey(0)
cv2.destroyAllWindows()

example of image

We can start with segment each color (Red, Green, Blue and Dark Red) to respective separate masks using cv2.inRange() and then we can combine all the mask to generate a single image where all the pixels with either Red, Green, Blue or Dark Red pixels are marked. Then we can simply overlay the input image on white canvas where we have found the desired pixels. You can have a look at the following code to get more understanding:

import cv2
import numpy as np

original_image = cv2.imread("/path/to/your/img.png")
t = 10  # tolerance

orange_thresh = cv2.inRange(original_image, np.array([77 - t, 151 - t, 255 - t]), np.array([77 + t, 151 + t, 255 + t]))
green_thresh = cv2.inRange(original_image, np.array([104 - t, 214 - t, 99 - t]), np.array([104 + t, 214 + t, 99 + t]))
red_1_thresh = cv2.inRange(original_image, np.array([50 - t, 60 - t, 242 - t]), np.array([50 + t, 60 + t, 242 + t]))
red_2_thresh = cv2.inRange(original_image, np.array([31 - t, 31 - t, 129 - t]), np.array([31 + t, 31 + t, 129 + t]))

combined_mask = orange_thresh + green_thresh + red_1_thresh + red_2_thresh
combined_mask_inv = 255 - combined_mask

combined_mask_rgb = cv2.cvtColor(combined_mask_inv, cv2.COLOR_GRAY2BGR)

final = cv2.max(original_image, combined_mask_rgb)

cv2.imwrite("./debug.png", final)

Result:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM