如何使用Java OpenCV庫獲取影像的畫素(RGB值)?
數字影像儲存為畫素的二維陣列,畫素是數字影像的最小元素。
每個畫素包含alpha、紅、綠、藍的值,每個顏色的值介於0到255之間,佔用8位(2^8)。
ARGB值按相同的順序(從右到左)儲存在4個位元組的記憶體中,藍色值在0-7位,綠色值在8-15位,紅色值在16-23位,alpha值在24-31位。
檢索影像的畫素內容(ARGB值) -
要從影像中獲取畫素值 -
遍歷影像中的每個畫素。即執行巢狀迴圈遍歷影像的高度和寬度。
使用getRGB()方法獲取每個點的畫素值。
透過將畫素值作為引數傳遞來例項化Color物件。
分別使用getRed()、getGreen()和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,紅色為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;
廣告