如何使用Java OpenCV库获取图像的像素(RGB值)?

数字图像存储为像素的2D数组,像素是数字图像的最小元素。

每个像素包含alpha、红色、绿色、蓝色值,每个颜色值的范围在0到255之间,占用8位(2^8)。

ARGB值以相同的顺序(从右到左)存储在4个字节的内存中,蓝色值在0-7位,绿色值在8-15位,红色值在16-23位,alpha值在24-31位。

如何使用Java OpenCV库获取图像的像素(RGB值)?

检索图像的像素内容(ARGB值)-

要从图像中获取像素值-

  • 循环遍历图像中的每个像素。即运行嵌套循环遍历图像的高度和宽度。

  • 使用getRGB()方法获取每个点的像素值。

  • 通过将像素值作为参数传递,实例化Color对象。

  • 使用getRed()、getGreen()和getBlue()方法获取红色、绿色和蓝色值。

getBlue()方法分别。

示例

以下是Java的示例,读取图像的每个像素的内容,并将RGB值写入文件中 −

import java.io.File; import java.io.FileWriter; import java.awt.Color; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; public class GetPixels { public static void main(String args[])throws Exception { FileWriter writer = new FileWriter("D:Imagespixel_values.txt"); //Reading the image File file= new File("D:Imagescat.jpg"); BufferedImage img = ImageIO.read(file); for (int y = 0; y < img.getHeight(); y++) { for (int x = 0; x < img.getWidth(); x++) { //Retrieving contents of a pixel int pixel = img.getRGB(x,y); //Creating a Color object from pixel value Color color = new Color(pixel, true); //Retrieving the R G B values int red = color.getRed(); int green = color.getGreen(); int blue = color.getBlue(); writer.append(red+":"); writer.append(green+":"); writer.append(blue+""); writer.append("n"); writer.flush(); } } writer.close(); System.out.println("RGB values at each pixel are stored in the specified file"); } }登录后复制