2014-12-07 195 views
0

我正在从PNG中读取bufferedImages,并使用PixelGrabber将它们转换为int数组。我的问题是:我如何使用整数数组来制作相应的OpenCV Mat?阵列是1D,每个值代表一个像素的RGB值。如何将int []转换为OpenCV Mat? (反之亦然)

我已经尝试过使用字节数组。

+0

你是什么意思的组合RGB值是什么意思? – 2014-12-08 06:11:56

+0

什么是“组合RGB”?你的意思是int的第一个字节是你的R值,第二个G和th字节是B值?什么是最后的字节随机值?您可以将每个int读取为32位RGBA值。 – Micka 2014-12-08 06:58:17

+0

@Micka无论发生什么,当你从pixelGrabber读取像素时,我不完全确定存储在int中的数据。我所知道的是,要获得红色(rgbvalue >> 16)& 0xff;绿色其(rgbvalue >> 8)& 0xff;和蓝色是rgbvalue & 0xff;这是否有帮助? – 2014-12-08 22:16:06

回答

1

只是将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] 
+0

非常感谢你;事实上它需要成为BGR的一部分openCV,还是因为我定义int []的方式?我的意思是,几乎没有任何东西(我已经穿过)使用BGR代替RGB ... – 2014-12-10 20:45:19

+1

Afaik BGR字节顺序是大多数图像库(例如directX)中RGB图像的标准。例如,在显示图像时,OpenCV假定bgr排序 – Micka 2014-12-10 21:21:56

相关问题