gpt4 book ai didi

java - OpenCV获取特定颜色范围内的像素

转载 作者:行者123 更新时间:2023-12-02 09:14:23 26 4
gpt4 key购买 nike

我想使用 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 用作该行的输入参数,但是在转换时,我始终明确我使用的 channel 数,对于 hsv 我总是使用三。

为什么我会收到此错误?

最佳答案

之后

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

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

所以:

//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);

关于java - OpenCV获取特定颜色范围内的像素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59129927/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com