gpt4 book ai didi

java - 如何将 int[] 转换为 OpenCV Mat? (反之亦然)

转载 作者:行者123 更新时间:2023-12-01 12:09:23 30 4
gpt4 key购买 nike

我正在从 PNG 中读取 bufferedImages,并使用 PixelGrabber 将它们转换为 int 数组。那么我的问题是:如何使用整数数组来制作相应的OpenCV Mat?其中数组是一维的,每个值代表一个像素的组合 RGB 值。

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

最佳答案

只需将 32 位 int 值解释为 32 位 RGBA 值。我不知道为什么您不必更改 channel 的顺序,但使用 int 数组作为 cv::Mat 的输入,您会自动获得 BGRA 顺序。然后,如果需要,您只需删除 Alpha channel 即可。

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]

关于java - 如何将 int[] 转换为 OpenCV Mat? (反之亦然),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27347018/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com