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

WBOY
WBOY 转载
2023-08-19 12:57:03 969浏览

数字图像存储为像素的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:\Images\pixel_values.txt");
      //Reading the image
      File file= new File("D:\Images\cat.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");
   }
}

输出

RGB values at each pixel are stored in the specified file

你还可以使用移位运算符从像素中检索RGB值

要这样做,

  • 右移,将每个颜色的起始位置移动到相应的位置,例如alpha为24,red为16,等等。

  • 右移操作可能会影响其他通道的值,为了避免这种情况,你需要执行按位与操作与0Xff。这样可以屏蔽变量,只保留最后8位,并忽略其余所有位。

int p = img.getRGB(x, y);
//Getting the A R G B values from the pixel value
int a = (p>>24)&0xff;
int r = (p>>16)&0xff;
int g = (p>>8)&0xff;
int b = p&0xff;

以上就是如何使用Java OpenCV库获取图像的像素(RGB值)?的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除