Search code examples
pythonopencvchromakey

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


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


Solution

  • 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.