Python 如何将JPG图像的整数数组转换为JPG图像?
我在机器人上安装了摄像头。长话短说,摄像机输出二进制数组,我相信这是一个JPG编码的流。我这样说是因为我使用的库中的很多方法都暗示它是JPG编码的,第一个和最后两个字节分别是Python 如何将JPG图像的整数数组转换为JPG图像?,python,camera,jpeg,Python,Camera,Jpeg,我在机器人上安装了摄像头。长话短说,摄像机输出二进制数组,我相信这是一个JPG编码的流。我这样说是因为我使用的库中的很多方法都暗示它是JPG编码的,第一个和最后两个字节分别是255216和255217,这是JPG文件格式的神奇数字 如何将这个整数数组转换为Python中的JPG文件 我尝试将整数数组写入.JPG文件,但该文件被标记为已损坏 长话短说,我有一个连接到esp8266的ArduCam(可以连接到WiFi的Arduino板)。我有一个脚本可以捕获一张照片,并将原始图像数据上传到esp82
255216
和255217
,这是JPG文件格式的神奇数字
如何将这个整数数组转换为Python中的JPG文件
我尝试将整数数组写入.JPG文件,但该文件被标记为已损坏
长话短说,我有一个连接到esp8266的ArduCam(可以连接到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)) + ",";
}
}
}
现在我知道jpeg文件分别以255216和255217开始和结束。所以我认为这是个好兆头。此外,当我使用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)
import struct
...
for i in img:
tmpfile.write(struct.pack("B", i))
...