OpenCV获得特定颜色范围内的像素

问题描述 投票:0回答:1

我想使用OpenCV在android中获取特定颜色范围内的像素。

这是我初始化imageReader的方式(我正在使用RGBA):

    imageReader = ImageReader.newInstance(screenWidth, screenHeight, PixelFormat.RGBA_8888, 2);

这是我从imageReader处理图像的方式:

    Image image = reader.acquireLatestImage();

    //Create a Mat using 4 channels (since RGBA uses 4 channels) and fill it with the image-data.
    Mat rgba = new Mat(image.getHeight(), image.getWidth(), CvType.CV_8UC4); 
    ByteBuffer buffer = image.getPlanes()[0].getBuffer();
    byte[] bytes = new byte[buffer.remaining()];
    buffer.get(bytes);
    rgba.put(0, 0, bytes);

    //Range of colors to be detected:
    Scalar lower = new Scalar(10, 10, 100);
    Scalar upper = new Scalar(100, 100, 255);

    //Create a Mat using 3 channels (since HSV uses 3 channels)
    Mat hsv = new Mat(image.getHeight(), image.getWidth(), CvType.CV_8UC3);

    //Convert from source RGBA to destination HSV, the 3 specifes the channels for the destination Mat.
    Imgproc.cvtColor(rgba, hsv, Imgproc.COLOR_RGB2HSV, 3);

    //Do the filtering
    Core.inRange(hsv, lower, upper, hsv);

    //Convert back to RGBA (now i use 4 channels since the destination is RGBA)
    Imgproc.cvtColor(hsv, rgba, Imgproc.COLOR_HSV2RGB, 4); 

    image.close();           

但是在:

Imgproc.cvtColor(hsv, rgba, Imgproc.COLOR_HSV2RGB, 4); 

我收到错误:

cv::Exception: OpenCV(4.1.2) ...

    > Invalid number of channels in input image:
    >     'VScn::contains(scn)'
    > where
    >     'scn' is 1

hsv用作该行的输入参数,但是在转换时,我始终明确使用了多少通道,对于hsv,我始终使用三个通道。

我为什么会收到此错误?

java android opencv image-processing hsv
1个回答
0
投票

之后

//Do the filtering
Core.inRange(hsv, lower, upper, hsv);

矩阵hsv的类型为CV_8UC1,并且表示由inRange函数创建的二进制单通道掩码。

所以:

//Do the filtering
Mat mask = new Mat(hsv.rows(), hsv.cols(), CvType.CV_8U, new Scalar(0));
Core.inRange(hsv, lower, upper, mask);

// Set to (0,0,0) all pixels that are 0 in the mask, i.e. not in range
Core.bitwise_not( mask, mask);
hsv.setTo(new Scalar(0,0,0), mask);

//Convert back to RGBA (now i use 4 channels since the destination is RGBA)
Imgproc.cvtColor(hsv, rgba, Imgproc.COLOR_HSV2RGB, 4); 
热门问题
推荐问题
最新问题