我正在從PNG中讀取bufferedImages,並使用PixelGrabber將它們轉換爲int數組。我的問題是:我如何使用整數數組來製作相應的OpenCV Mat?陣列是1D,每個值代表一個像素的RGB值。如何將int []轉換爲OpenCV Mat? (反之亦然)
我已經嘗試過使用字節數組。
我正在從PNG中讀取bufferedImages,並使用PixelGrabber將它們轉換爲int數組。我的問題是:我如何使用整數數組來製作相應的OpenCV Mat?陣列是1D,每個值代表一個像素的RGB值。如何將int []轉換爲OpenCV Mat? (反之亦然)
我已經嘗試過使用字節數組。
只是將32位int值解釋爲32位RGBA值。我不知道爲什麼你不需要改變通道的順序,但是使用int數組作爲你的cv::Mat
的輸入,你會自動獲得BGRA排序。然後,如果需要,您只需刪除Alpha通道。
int main()
{
// the idea is that each int is 32 bit which is 4 channels of 8 bit color values instead of 3 channels, so assume a 4th channel.
// first I create fake intArray which should be replaced by your input...
const int imgWidth = 320;
const int imgHeight = 210;
int intArray[imgWidth*imgHeight]; // int array
// fill the array with some test values:
for(unsigned int pos = 0; pos < imgWidth*imgHeight; ++pos)
intArray[pos] = 8453889; // 00000000 10000000 11111111 00000001 => R = 128, G = 255, B = 1
//intArray[pos] = 65280; // green
//intArray[pos] = 16711680; // red
//intArray[pos] = 255; // blue
// test:
int firstVal = intArray[0];
std::cout << "values: " << " int: " << firstVal << " R = " << ((firstVal >> 16) & 0xff) << " G = " << ((firstVal >> 8) & 0xff) << " B = " << (firstVal & 0xff) << std::endl;
// here you create the Mat and use your int array as input
cv::Mat intMat_BGRA = cv::Mat(imgHeight,imgWidth,CV_8UC4, intArray);
// now you have a 4 channel mat with each pixel is one of your int, but with wrong order...
std::cout << "BGRA ordering: " << intMat_BGRA.at<cv::Vec4b>(0,0) << std::endl;
// this is in fact the BGRA ordering but you have to remove the alpha channel to get BGR values:
// (unless you can live with BGRA values => you have to check whether there is garbage or 0s/255s in the byte area
// so split the channels...
std::vector<cv::Mat> BGRA_channels;
cv::split(intMat_BGRA, BGRA_channels);
// remove the alpha channel:
BGRA_channels.pop_back();
// and merge back to image:
cv::Mat intMat_BGR;
cv::merge(BGRA_channels, intMat_BGR);
std::cout << "BGR ordering: " << intMat_BGR.at<cv::Vec3b>(0,0) << std::endl;
cv::imshow("ordereed", intMat_BGR);
cv::waitKey(0);
return 0;
}
給我輸出:
values: int: 8453889 R = 128 G = 255 B = 1
BGRA ordering: [1, 255, 128, 0]
BGR ordering: [1, 255, 128]
非常感謝你;事實上它需要成爲BGR的一部分openCV,還是因爲我定義int []的方式?我的意思是,幾乎沒有任何東西(我已經穿過)使用BGR代替RGB ... – 2014-12-10 20:45:19
Afaik BGR字節順序是大多數圖像庫(例如directX)中RGB圖像的標準。例如,在顯示圖像時,OpenCV假定bgr排序 – Micka 2014-12-10 21:21:56
你是什麼意思的組合RGB值是什麼意思? – 2014-12-08 06:11:56
什麼是「組合RGB」?你的意思是int的第一個字節是你的R值,第二個G和th字節是B值?什麼是最後的字節隨機值?您可以將每個int讀取爲32位RGBA值。 – Micka 2014-12-08 06:58:17
@Micka無論發生什麼,當你從pixelGrabber讀取像素時,我不完全確定存儲在int中的數據。我所知道的是,要獲得紅色(rgbvalue >> 16)& 0xff;綠色其(rgbvalue >> 8)& 0xff;和藍色是rgbvalue & 0xff;這是否有幫助? – 2014-12-08 22:16:06