3

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

4

2 回答 2

2

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.

于 2021-04-12T15:21:07.733 回答
1

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

于 2021-04-12T16:07:58.413 回答