java - OpenCV获取特定颜色范围内的像素
问题描述
我想使用 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
我总是使用三个。
为什么我会收到此错误?
解决方案
后
//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);
推荐阅读
- c# - 比较 Web 服务响应
- node.js - 如何使用 AWS Lamba 函数获取和返回日期
- c++ - C ++ objcopy使类方法变弱
- python - 安装 Keras 破坏了 Conda 虚拟环境(Windows 10)
- amazon-dynamodb - 单独的表与地图列表 - DynamoDB
- android - 如何在不读取 android 上的 nfc 的情况下获取手机的唯一 nfc id?
- mongodb - 如何在 MongoDB 的数组中添加对象?
- go - 无法解组 YAML 结构
- google-maps - 谷歌地图嵌入 iframe
- android - 如何将当前日期设置为 sqlite 中的数据库表名?