我在机器人上安装了摄像头。长话短说,相机输出二进制数组,我相信这是JPG编码的流。我之所以这样说是因为我正在使用的库中的许多方法都暗示了它是JPG编码的,并且前2个字节和后2个字节分别是255 216
和255 217
,它们是JPG的幻数。文件格式。
如何在Python中将此整数数组转换为JPG文件?
我曾尝试将整数数组写入.JPG文件,但该文件被标记为已损坏。
长话短说,我有一个ArduCam连接到esp8266(实际上是可以连接到WiFi的Arduino板)。我有一个脚本捕获照片,并将原始图像数据上传到esp8266托管的服务器。这是我使用的主要方法:
void camCapture(ArduCAM myCAM) {
WiFiClient client = server.client(); // ignore this stuff
uint32_t len = myCAM.read_fifo_length();
if (len >= MAX_FIFO_SIZE) //8M
{
Serial.println(F("Over size."));
}
if (len == 0 ) //0 kb
{
Serial.println(F("Size is 0."));
}
myCAM.CS_LOW();
myCAM.set_fifo_burst();
if (!client.connected()) return;
String response = "[";
i = 0;
while ( len-- ) // this is where the raw image is collection
{
temp_last = temp;
temp = SPI.transfer(0x00);
//Read JPEG data from FIFO
if ( (temp == 0xD9) && (temp_last == 0xFF) ) //If find the end ,break while,
{
buffer[i++] = temp; //save the last 0XD9
response += String(int(temp)) + "], ";
response += String(i);
if (!client.connected()) break;
Serial.print(String(i));
server.send(200,"text/plain",response); // this is where the image is uploaded
is_header = false;
i = 0;
myCAM.CS_HIGH();
break;
}
if (is_header == true)
{
//Write image data to buffer if not full
if (i < bufferSize)
buffer[i++] = temp;
else
{
//Write bufferSize bytes image data to file
if (!client.connected()) break;
i = 0;
buffer[i++] = temp;
}
response += String(int(temp)) + ",";
}
else if ((temp == 0xD8) & (temp_last == 0xFF))
{
is_header = true;
buffer[i++] = temp_last;
buffer[i++] = temp;
response += String(int(temp_last)) + "," + String(int(temp)) + ",";
}
}
}
原始图像数据如下:
255,216,255,224,0,16,74,70,73,70,0,1,1,1,0,0,0,0,0,0,255,219,74,74,74,74,74,74,74,74,74,74,74,74,74,74 [...] 64,143,255,217
现在,我知道jpeg文件的开头和结尾分别为255,216和255,217。因此,我认为这是一个好兆头。此外,当我使用jpeg html代码时,它实际上将原始图像数据转换为实际图像。
这是我的python脚本,在这里我尝试将原始图像数据解码为.jpg文件:
import cv2
with open('img.txt') as file: # this is where I keep the raw image data
img = file.read()
img = img.split(',')
img = [int(i) for i in img]
tmpfile = open("tmp.jpg", "wb")
for i in img:
tmpfile.write(bytes(i))
tmpfile.close()
img = cv2.imread('tmp.jpg')
print(img)
cv2.imshow('img',img)
cv2.waitKey(0)
您正在将值的字符串表示形式(即"2"
,"5"
和"5"
而不是0xFF
)转储到文件中,因为bytes()
会将int
转换为字节字符串。您可能已经注意到,从文件大小来看,它与tmp.txt
中的值数量不匹配。
将字节写入文件的正确方法如下:
import struct
...
for i in img:
tmpfile.write(struct.pack("B", i))
...
由于在这种情况下使用8位值,因此也可以使用chr(i)
。