首頁  >  文章  >  Java  >  如何使用Java OpenCV庫取得影像的像素(RGB值)?

如何使用Java OpenCV庫取得影像的像素(RGB值)?

WBOY
WBOY轉載
2023-08-19 12:57:031798瀏覽

數位影像儲存為像素的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值寫入檔案中−

Live Demo-->
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.com。如有侵權,請聯絡admin@php.cn刪除