Python脚本将图像转换为字节数组
我正在写一个Python脚本,想要批量上传照片。我的目标是读取一张图片,并把它转换成字节数组。如果你有什么建议,我会非常感激。
#!/usr/bin/python
import xmlrpclib
import SOAPpy, getpass, datetime
import urllib, cStringIO
from PIL import Image
from urllib import urlopen
import os
import io
from array import array
""" create a proxy object with methods that can be used to invoke
corresponding RPC calls on the remote server """
soapy = SOAPpy.WSDL.Proxy('localhost:8090/rpc/soap-axis/confluenceservice-v2?wsdl')
auth = soapy.login('admin', 'Cs$corp@123')
5 个回答
0
#!/usr/bin/env python
#__usage__ = "To Convert Image pixel data to readable bytes"
import numpy as np
import cv2
from cv2 import *
class Image2ByteConverter(object):
def loadImage(self):
# Load image as string from file/database
file = open('Aiming_ECU_Image.png', "rb")
return file
def convertImage2Byte(self):
file = self.loadImage()
pixel_data = np.fromfile(file, dtype=np.uint8)
return pixel_data
def printData(self):
final_data = self.convertImage2Byte()
pixel_count = 0
for data in final_data:
pixel_count += 1
print("Byte ", pixel_count,": ", int(data))
def run(self):
# self.loadImage()
# self.convertImage2Byte()
self.printData()
if __name__ == "__main__":
Image2ByteConverter().run()
这个方法对我有效。
前提条件:
python -m pip install opencv-python
python -m pip install numpy
6
with BytesIO() as output:
from PIL import Image
with Image.open(filename) as img:
img.convert('RGB').save(output, 'BMP')
data = output.getvalue()[14:]
我只是用这个方法在Windows系统中把图片添加到剪贴板。
16
我不知道怎么把它转换成字节数组,但把它转换成字符串很简单:
import base64
with open("t.png", "rb") as imageFile:
str = base64.b64encode(imageFile.read())
print str
20
这个对我有效
# Convert image to bytes
import PIL.Image as Image
pil_im = Image.fromarray(image)
b = io.BytesIO()
pil_im.save(b, 'jpeg')
im_bytes = b.getvalue()
90
使用 bytearray
:
with open("img.png", "rb") as image:
f = image.read()
b = bytearray(f)
print b[0]
你还可以看看 struct,它可以进行很多类似的转换。