先将BufferedImage统一转化为RGB格式,再将其转换为Mat类型。
package site.zytech.picturematch.tools; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import javax.imageio.ImageIO; import java.awt.color.ColorSpace; import java.awt.image.BufferedImage; import java.awt.image.ColorConvertOp; import org.bytedeco.opencv.opencv_core.Mat; import static org.bytedeco.opencv.global.opencv_core.*; import static org.bytedeco.opencv.global.opencv_highgui.*; import static org.bytedeco.opencv.global.opencv_imgproc.*; /** * @author 作者: Alderaan * @version 创建时间:2022年1月25日 下午4:40:52 * */ public class testconvert { /** * BufferedImage均转为TYPE_3BYTE_BGR,RGB格式 * * @param input 未知格式BufferedImage图片 * @return TYPE_3BYTE_BGR格式的BufferedImage图片 */ public static BufferedImage converttoRGBformat(BufferedImage input) { if (null == input) { throw new NullPointerException("BufferedImage input can not be null!"); } if (BufferedImage.TYPE_3BYTE_BGR != input.getType()) { BufferedImage input_rgb = new BufferedImage(input.getWidth(), input.getHeight(), BufferedImage.TYPE_3BYTE_BGR); new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_sRGB), null).filter(input, input_rgb); return input_rgb; } else { return input; } } public static void main(String[] args) throws IOException, URISyntaxException, InterruptedException { BufferedImage bimg1 = null; try { bimg1 = ImageIO.read(new File("/Lena.png")); // 修改为自己图片的路径 } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } bimg1 = converttoRGBformat(bimg1); // BufferedImage convert to TYPE_3BYTE_BGR(RGB格式) byte[] image_rgb = (byte[]) bimg1.getData().getDataElements(0, 0, bimg1.getWidth(), bimg1.getHeight(), null); Mat bimg1_mat; bimg1_mat = new Mat(bimg1.getHeight(), bimg1.getWidth(), CV_8UC3); bimg1_mat.data().put(image_rgb); cvtColor(bimg1_mat, bimg1_mat, COLOR_RGB2BGR); // RGB转BGR imshow("Lena", bimg1_mat); waitKey(0); } }