【OpenCV】 Java获取像素点的RGB值

今天照着大佬视频写了个图片显示器,一点点的java图形界面知识就可以啦

public class ImageUI extends JComponent{
	private BufferedImage image;
	public ImageUI() {
		this.image = null;
	}
	
	@Override
	protected void paintComponent(Graphics g) {   
		Graphics2D g2d = (Graphics2D)g;
		if(image == null) {
			g2d.setPaint(Color.BLACK);
			g2d.fillRect(0, 0, this.getWidth(), this.getHeight());
		}else {
			g2d.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
		}
	}
	
	public void imshow(String title,Mat src) {
		this.image = convert2BufferedImage(src);
		JDialog ui = new JDialog();
		ui.getContentPane().setLayout(new BorderLayout());
		ui.getContentPane().add(this, BorderLayout.CENTER);
		ui.setTitle(title);
		ui.setSize(image.getWidth(), image.getHeight());
		ui.setVisible(true);
		this.repaint();		//重新加载
	}

	private BufferedImage convert2BufferedImage(Mat src) {
		// TODO Auto-generated method stub
		int width = src.cols();
		int height = src.rows();
		int dims = src.channels();
		byte[] data = new byte[width * height * dims];
		src.get(0, 0, data);
		int[] pixels = new int[width * height];
		
		BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_INT_ARGB);
		int r = 0, g = 0, b = 0;
		int index = 0;
		for(int row = 0; row < height; row++) {
			for(int col = 0; col < width; col++) {
				index = row * width * dims + col * dims;
				if(dims == 3) {
					b = data[index]&0xff;
					g = data[index+1]&0xff;
					r = data[index+2]&0xff;
					pixels[row * width + col] = ((255&0xff) << 24) | ((r&0xff) << 16) | ((g&0xff) << 8) | (b&0xff);
				}else if(dims == 1) {
					b = data[index]&0xff;
					pixels[row * width + col] = ((255&0xff) << 24) | ((b&0xff) << 16) | ((b&0xff) << 8) | (b&0xff);
				}
			}
		}
		bi.getRaster().setDataElements(0, 0, width, height, pixels);
		return bi;
	}
}

有了这个的话,就更加直观啦! 

【OpenCV】 Java获取像素点的RGB值 

其实也就是将图片的RGB信息放进pixel里面,获取像素点的RGB值

PS :1. &0xff 为了保证二进制数据的一致性(在上一篇博文已经提过 点此查看

         2. ((255&0xff) << 24) | ((r&0xff) << 16) | ((g&0xff) << 8) | (r&0xff) 移位问题,不再赘述,如下(一个pixel的位数);

【OpenCV】 Java获取像素点的RGB值