簡體   English   中英

Python 將圖像轉換為字節數組的腳本

[英]Python Script to convert Image into Byte array

我正在編寫一個 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')

使用bytearray

with open("img.png", "rb") as image:
  f = image.read()
  b = bytearray(f)
  print b[0]

您還可以查看一下可以執行此類轉換的struct

我不知道轉換成字節數組,但很容易將其轉換為字符串:

import base64

with open("t.png", "rb") as imageFile:
    str = base64.b64encode(imageFile.read())
    print str

資源

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中的剪貼板中。

這適合我

# 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()
return im_bytes
#!/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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM