Reputation: 45
I have a problem with conversion from BGR to HSV. I'm programming with Android Studio and testing with my Xperia Z5.
In my code snippet, I'm getting totally wrong colour values:
Scalar LOWER_RED = (0,0,0);
Scalar HIGHER_RED = (30,255,255);
Mat src = new Mat(Bitmap.getHeight(), Bitmap.getWidth(),CvType.CV_8UC4);
Mat hsv = new Mat(Bitmap.getHeight(), Bitmap.getWidth(),CvType.CV_8UC4);
Utils bitmapToMat(Bitmap, src);
Imgproc.cvtColor(src,hsv,Imgproc.COLOR_BGR2HSV);
Core.inRange(hsv, LOWER_RED, HIGHER_RED, hsv);
Utils.matToBitmap(hsv,Bitmap);
I want to capture red colour. What did I do wrong?
Edit: I tried with all advices and my Code Snippet looks now this way:
Scalar LOWER_RED = (0,10,100);
Scalar HIGHER_RED = (10,255,255);
Mat src = new Mat(Bitmap.getHeight(), Bitmap.getWidth(),CvType.CV_8UC3);
Mat hsv = new Mat(Bitmap.getHeight(), Bitmap.getWidth(),CvType.CV_8UC3);
Utils bitmapToMat(Bitmap, src);
Imgproc.cvtColor(src,hsv,Imgproc.COLOR_BGR2HSV);
Core.inRange(hsv, LOWER_RED, HIGHER_RED, hsv);
Utils.matToBitmap(hsv,Bitmap);
The Outcome is a black screen ( no matches )
with
Core.inRange(hsv,New Scalar(0,0,0),New Scalar(10,255,255),HighRedRange);
Core.inRange(hsv,New Scalar(160,100,100),New Scalar(179,255,255),LowRedRange);
Core.addWeighted(LowRedRange,1.0,HighredRange,1.0,0.0,hsv);
The vegetables are black and the white background is white in hsv 0,0,0 - 10,255,255 AND 160,100,100 - 179,255,255
If I use a Scalar from 110,100,100 until 135,255,255, then the red pepper is white and the back ground black ( correctly detected ).
Source Picture:
And I dont understand all this...
Upvotes: 2
Views: 1468
Reputation: 45
I know now my problem it's this:
Imgproc.cvtColor(src,hsv,Imgproc.COLOR_BGR2HSV);
With RGB2HSV all values are correct. I thought on Android Smartphones there is BGR used ?
However, Big thanks for all answers.
I wish all of you a great day :)
Upvotes: 1
Reputation: 762
There is a good tutorial here. It's for C++ but the general idea is the same. I tried the general idea and it surely works. The problem is that your range is too broad. In OpenCV, Hue range is in 0-180. Meaning that your higher limit goes to 30*2 = 60 which includes nearly all yellow range too.
I set the range from 0 to 10 for Hue, but remember you may also want to get 160 - 179 range which also includes some part of red. For this, you just need a second mask and then combine them with simple addition.
The example code in Python:
import cv2
import numpy as np
img = cv2.imread('peppers.jpg',1)
im_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
thresh_low = np.array([0,100,100])
thresh_high = np.array([10,255,255])
mask = cv2.inRange(im_hsv, thresh_low, thresh_high)
im_masked = cv2.bitwise_and(img,img, mask= mask)
cv2.imshow('Masked',im_masked)
cv2.waitKey(0)
Original image:
Result:
Upvotes: 2