我想將String類型的數據變量存儲在內存中,這些變量實際上是圖像的十六進制代碼。所以會有一個2D動態數組,它在運行時存儲數據。 我試着下面的代碼來填充數據,首先創建指針指向動態數組,如下所示。在2D動態數組中填充數據
//dynamic allocation of array
int row = rows - 1;
int col = cols - 1;
Mat img = image;
cout << " row " << row << " col " << col <<endl;
String **matrix;
matrix= new String*[row]; // dynamic array (size 10) of pointers to int
for (int i = 0; i < 10; ++i) {
matrix[i] = new String[col];
// each i-th pointer is now pointing to dynamic array (size 10) of actual int values
}
在這裏,如果我沒有錯,我得到了堆上的內存。所以我編寫嵌套循環來提取RGB信息,轉換爲十六進制字符串並存儲在數組中。
for (int r = 0; r <= row; r++) {
cout << endl;
for (int c = 0; c <= col; c++)
{
Vec3b intensity = img.at<Vec3b>(r, c);
uchar blue = intensity.val[0];
int b = (int)blue;
uchar green = intensity.val[1];
int g = (int)green;
uchar red = intensity.val[2];
int r = (int)red;
//filling dynamic array
matrix[row][col] = RGBToHex(r,g,b);
}
}
這裏是我將RGB轉換爲十六進制字符串的方法。
string RGBToHex(int rNum, int gNum, int bNum)
{
// returns 6 digit hex code
string result;
char r[255];
sprintf_s(r, "%.2X", rNum);
result.append(r);
char g[255];
sprintf_s(g, "%.2X", gNum);
result.append(g);
char b[255];
sprintf_s(b, "%.2X", bNum);
result.append(b);
return result;
}
我試圖提取RGB信息,轉換爲十六進制字符串,店.txt文件,它的工作原理,但下面的例外是當我試圖填補數組拋出。
請重點突出問題,讓我知道我錯在哪裏。
**Exception thrown at 0x000007FEE1AD7330 (opencv_world310.dll) in ImageDecoder.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF.
If there is a handler for this exception, the program may be safely continued.**
它工作正常,我將十六進制信息打印到.txt文件中進行測試。 –
加索引你的矩陣應該是'matrix [r] [c]',因爲那些是運行變量。 'matrix [row] [col]'仍然會導致overindexing。 – winnetou
^編輯回答與數字來澄清。 –