我正在尝试将rgb图像的颜色空间从RGB转换为HSV。我使用了以下代码:
public class Main {
public static void main( String[] args )
{
try{
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
File input = new File("H:/Development/workspace/label.png");
BufferedImage image = ImageIO.read(input);
byte[] data=extractBytes(image);
Mat mat = new Mat(image.getHeight(),image.getWidth(),CvType.CV_8UC2);
mat.put(0, 0, data);
Mat mat1 = new Mat(image.getHeight(),image.getWidth(),CvType.CV_8UC2);
Imgproc.cvtColor(mat, mat1, Imgproc.COLOR_RGB2HSV);
byte[] data1 = new byte[mat1.rows()*mat1.cols()*(int)(mat1.elemSize())];
mat1.get(0, 0, data1);
BufferedImage image1 = new BufferedImage(mat1.cols(), mat1.rows(), 5);
image1.getRaster().setDataElements(0,0,mat1.cols(),mat1.rows(),data1);
File ouptut = new File("H:/Development/workspace/label_hsv.png");
ImageIO.write(image1, "png", ouptut);
} catch (Exception e) {
// System.out.println("Failed");
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
}
}
public static byte[] extractBytes (BufferedImage bufferedImage) throws IOException {
WritableRaster raster = bufferedImage .getRaster();
DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
return ( data.getData() );
}
}
但它失败并出现一些错误:断言失败
OpenCV Error: Assertion failed ((scn == 3 || scn == 4) && (depth == CV_8U || depth == CV_32F)) in cv::cvtColor, file ..\..\..\..\opencv\modules\imgproc\src\color.cpp, line 3959
CvException [org.opencv.core.CvException: cv::Exception: ..\..\..\..\opencv\modules\imgproc\src\color.cpp:3959: error: (-215) (scn == 3 || scn == 4) && (depth == CV_8U || depth == CV_32F) in function cv::cvtColor
]
at org.opencv.imgproc.Imgproc.cvtColor_1(Native Method)
at org.opencv.imgproc.Imgproc.cvtColor(Imgproc.java:4598)
at com.pradeep.exper.Main.main(Main.java:28)
为什么会这样?
答案 0 :(得分:5)
到目前为止,您的程序可以归结为一个简单的:
public class Main {
public static void main( String[] args ) {
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
Mat bgr = Highgui.imread("H:/Development/workspace/label.png");
Mat hsv = new Mat();
Imgproc.cvtColor(bgr, hsv, Imgproc.COLOR_RGB2HSV);
Highgui.imwrite("H:/Development/workspace/label_hsv.png");
}
}