Java将BufferedImage对象转为javacv中的Mat类型

思路

先将BufferedImage统一转化为RGB格式,再将其转换为Mat类型。

Java实现代码

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

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值