In the following code, I have carried out the following steps:
- Loaded an image from sdcard.
Converted it to HSV format.
Used
inRangefunction to mask out the red color.
Used
findContoursto find the contours.Find the largest contour from those contours.
Created an ROI around the largest contour using
boundingRectandsubmatfunctions.
- Converted this ROI Mat to HSV format.
Iterated through the ROI Mat, and check for each pixel if it lies within the largest contour. I used the method
pointPolygonTestto find this out, but it returns-1for every pixel, as can be seen from theLog.ioutput I have pasted here. The question is why? How can I correct this.private Scalar detectColoredBlob() { rgbaFrame = Highgui.imread("/mnt/sdcard/DCIM/rgbaMat4Mask.bmp"); Mat hsvImage = new Mat(); Imgproc.cvtColor(rgbaFrame, hsvImage, Imgproc.COLOR_BGR2HSV); Highgui.imwrite("/mnt/sdcard/DCIM/hsvImage.bmp", hsvImage);// check Mat maskedImage = new Mat(); Core.inRange(hsvImage, new Scalar(0, 100, 100), new Scalar(10, 255, 255), maskedImage); Highgui.imwrite("/mnt/sdcard/DCIM/maskedImage.bmp", maskedImage);// check List<MatOfPoint> contours = new ArrayList<MatOfPoint>(); Imgproc.findContours(maskedImage, contours, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE); // \/ We will use only the largest contour. Other contours (any other possible blobs of this color range) will be ignored. MatOfPoint largestContour = contours.get(0); double largestContourArea = Imgproc.contourArea(largestContour); for (int i = 1; i < contours.size(); ++i) {// NB Notice the prefix increment. MatOfPoint currentContour = contours.get(i); double currentContourArea = Imgproc.contourArea(currentContour); if (currentContourArea > largestContourArea) { largestContourArea = currentContourArea; largestContour = currentContour; } } MatOfPoint2f largestContour2f = new MatOfPoint2f(largestContour.toArray());// Required on Line 289. See http://stackoverflow.com/questions/11273588/how-to-convert-matofpoint-to-matofpoint2f-in-opencv-java-api Rect detectedBlobRoi = Imgproc.boundingRect(largestContour); Mat detectedBlobRgba = rgbaFrame.submat(detectedBlobRoi); Highgui.imwrite("/mnt/sdcard/DCIM/detectedBlobRgba.bmp", detectedBlobRgba);// check Mat detectedBlobHsv = new Mat(); Imgproc.cvtColor(detectedBlobRgba, detectedBlobHsv, Imgproc.COLOR_BGR2HSV); Highgui.imwrite("/mnt/sdcard/DCIM/roiHsv.bmp", detectedBlobHsv);// check for (int firstCoordinate = 0; firstCoordinate < detectedBlobHsv.rows(); firstCoordinate++) { for (int secondCoordinate = 0; secondCoordinate < detectedBlobHsv.cols(); secondCoordinate++) { Log.i(TAG, "HAPPY " + Arrays.toString(detectedBlobHsv.get(firstCoordinate, secondCoordinate))); if (Imgproc.pointPolygonTest(largestContour2f, new Point(firstCoordinate, secondCoordinate), false) == -1) { Log.i(TAG, "HAPPY ....................... OUTSIDE"); } } } Highgui.imwrite("/mnt/sdcard/DCIM/processedcontoured.bmp", detectedBlobHsv);// check



