Why I can't get the red color of tomatoes out of image?

274 views Asked by At

I tried a code from stackoverflow but it shows black color for me. what I want to do is:

Get Tomatoes white and other things black of this image

Salad with red tomatoes

To get red colors out of this image I used this code:

import cv2
import numpy as np

img = cv2.imread('test.png')

img = np.copy(img)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

lower_red = np.array([217, 25, 0])
upper_red = np.array([254, 217, 196])

mask = cv2.inRange(hsv, lower_red, upper_red)
#mask = cv2.bitwise_not(mask)

cv2.imwrite('mask.png', mask)
cv2.destroyAllWindows()

result is this

Black.

thank you for reading

2

There are 2 answers

0
Roland Deschain On BEST ANSWER

The following adaptation from your code:

import cv2
import numpy as np

img = cv2.imread('test2.png')


img = np.copy(img)
rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

lower_red = np.array([225, 0, 0])
upper_red = np.array([255, 200, 200])

mask = cv2.inRange(rgb, lower_red, upper_red)

cv2.imwrite('mask.png', mask)
cv2.destroyAllWindows()

produces this output: enter image description here

I simply removed the conversion to HSV (which is not necessary and I guess your initial lower and upper limits where thought to be for RGB anyway?). I played around a bit with the limits, but I guess, if you tinker a bit more with them, you can get better results.

0
Red On

Try this HSV mask:

import cv2
import numpy as np

img = cv2.imread("tomato.jpg")

lower = np.array([0, 55, 227])
upper = np.array([21, 255, 255])

mask = cv2.inRange(cv2.cvtColor(img, cv2.COLOR_BGR2HSV), lower, upper)
cv2.imshow("Image", mask)
cv2.waitKey(0)

Output:

enter image description here