我需要转换base64 to opencv::mat
文件。因此,我从视频中提取了一组10帧,并附加了base64(A)
(在python中使用base64.b64encode
)。
之后,我使用了here中的代码将base64转换为Mat。图像看起来不错。
但是它们的文件大小比原始图像大,而且当我将这些最终图像编码为base64(B)
(在python中使用base64.b64encode
)时,编码的base64与原始base64(A)
不同。我不明白为什么?这也影响了使用cv::mat
输出的应用程序的输出。
对于base64 to Mat
,我使用的是here中的代码(如上所述)。
编辑后的:以下是我的python脚本,用于转换jpeg to base64
(.txt)集
def img2txt(file_directory):
imageFiles = glob.glob(file_directory+"/*.jpg")
imageFiles.sort()
fileWrite='base64encoding.txt'
#print fileWrite
for i in range(0,len(imageFiles)):
image = open(imageFiles[i],'rb')
image_read = image.read()
image_64_encode = base64.b64encode(image_read)
with open (fileWrite, 'a') as f:
f.writelines(image_64_encode+'\n')
base64解码函数:来自here
static const std::string base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
static inline bool is_base64(unsigned char c) {
return (isalnum(c) || (c == '+') || (c == '/'));
}
std::string base64_decode(std::string const& encoded_string) {
int in_len = encoded_string.size();
int i = 0;
int j = 0;
int in_ = 0;
unsigned char char_array_4[4], char_array_3[3];
std::string ret;
while (in_len-- && (encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
char_array_4[i++] = encoded_string[in_]; in_++;
if (i == 4) {
for (i = 0; i < 4; i++)
char_array_4[i] = base64_chars.find(char_array_4[i]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (i = 0; (i < 3); i++)
ret += char_array_3[i];
i = 0;
}
}
if (i) {
/*for (j = i; j < 4; j++)
char_array_4[j] = 0;*/
for (j = 0; j < i; j++)
char_array_4[j] = base64_chars.find(char_array_4[j]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
//char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (j = 0; (j < i - 1); j++)
ret += char_array_3[j];
}
return ret;
}
C++主要功能:
int main()
{
ifstream in("TestBase64.txt");
if(!in) {
cout << "Cannot open input file.\n";
return 1;
}
int i=0;
string encoded_string;
while (getline(in, encoded_string))
{
string decoded_string = base64_decode(encoded_string);
vector<uchar> data(decoded_string.begin(), decoded_string.end());
cv::imwrite("/Frames_from_B_to_Mat/Frames_from_B_to_Mat"+b+".jpg");
i++;
}
return 0;
}
最佳答案
在线上:
vector<uchar> data(decoded_string.begin(), decoded_string.end());
您大概将一张图像的JPEG编码表示形式保留在
data
中。因此,您也可以将其写入二进制文件,而不要使用用于将Mat写入文件的cv::imwrite()
。如果出于某种莫名其妙的原因要使用
cv::imwrite()
,则需要将其传递给Mat
。因此,您最终将JPEG表示解码为Mat,然后编码为JPEG并写入-这似乎很愚蠢:cv::Mat img = cv::imdecode(data, cv::IMREAD_COLOR);
cv::imwrite('result.jpg',img);
TLDR;
我的意思是您的数据已经过JPEG编码,您可以从JPEG文件中读取数据。
关于c++ - 同一张图片使用不同的base64编码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54072321/