有兩種方法可以做到這一點:一個讀取像素之一,或者得到一個矩形的所有像素爲Java對整個圖像,然後用更大的陣列工作。哪一個最好取決於矩形的大小。下面的代碼首先將圖像的指定rect部分獲取到Java數組中。
import java.awt.Color;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Rect;
import org.opencv.highgui.Highgui;
public class OpenCVThing
{
public static void main(String[] args)
{
String opencvpath = System.getProperty("user.dir") + "\\lib\\";
System.load(opencvpath + Core.NATIVE_LIBRARY_NAME + ".dll");
// Get the whole rect into smallImg
Mat firstImage = Highgui.imread("capture.png");
System.out.println("total pxels:" + firstImage.total());
// We are getting a column 30 high and 30 wide
int width = 30;
int height = 30;
Rect roi = new Rect(120, 160, width, height);
Mat smallImg = new Mat(firstImage, roi);
int channels = smallImg.channels();
System.out.println("small pixels:" + smallImg.total());
System.out.println("channels:" + smallImg.channels());
int totalBytes = (int)(smallImg.total() * smallImg.channels());
byte buff[] = new byte[totalBytes];
smallImg.get(0, 0, buff);
// assuming it's of CV_8UC3 == BGR, 3 byte/pixel
// Effectively assuming channels = 3
for (int i=0; i< height; i++)
{
// stride is the number of bytes in a row of smallImg
int stride = channels * width;
for (int j=0; j<stride; j+=channels)
{
int b = buff[(i * stride) + j];
int g = buff[(i * stride) + j + 1];
int r = buff[(i * stride) + j + 2];
float[] hsv = new float[3];
Color.RGBtoHSB(r,g,b,hsv);
// Do something with the hsv.
System.out.println("hsv: " + hsv[0]);
}
}
}
}
注1:在這種情況下,在淺黃色每個字節表示一個像素的第三,因爲我假定格式是CV_8UC3。
total pxels:179305
small pixels:900
channels:3
hsv: 0.5833333
hsv: 0.5833333
hsv: 0.5833333
hsv: 0.5833333
hsv: 0.5833333
etc ...
見this page和docs的更詳細一點
的'CvRect收費=新CvRect(firstImage.get:
代碼是在這個答案與下面的輸出的屏幕截圖測試(160,120,30,30));''實際上並沒有用於獲取CvRect無法將其作爲參數的圖像,我在我的問題中使用它來證明我想獲取該圖像的該區域。 – cuber
我得到的圖像我不確定'CV類型'我使用的圖像是,我從視頻捕獲的幀中獲取圖像,然後嘗試獲取該圖像的值。這就是'mat2Img.getImage(mat2Img.mat);'它是Mat2Image的一個對象。 – cuber
firstImage.type();將返回一個int,它表示http://docs.opencv.org/2.4/modules/core/doc/basic_structures.html#mat-type上的類型之一不知道如何轉換Java中的數字。 –