0

我有一个 base64 图像,我想在给定高度将图像切割成 2 个或更多部分。在 python 中最有效的方法是什么?

一种方法是将base64转换为base64->bytes->ndarray->bytes。但是我在 ndarray->bytes 转换中遇到了问题。

from scipy import ndimage
import base64,io
import numpy as np
import matplotlib.pyplot as plt

i1 = 'base64 of your sample png image'
b64=i1.replace('data:image/png;base64,','')
byts = io.BytesIO(base64.b64decode(b64)) # base64->bytes conversion
img_array = ndimage.imread(byts)   #bytes->ndarray conversion
part1=img_array[0:100]
part2=img_array[100:150]

# now i want to convert part1 and part2 to bytes, but how ?
part1_bytes = part1.tobytes()
# but when I save part1_bytes into a file and open it in my pc, it says an invalid image

分割图像后,我想将每个部分转换为缓冲区。我想不通怎么做。即使我可以进行所有这些转换,它似乎也非常间接且冗长。我想知道如何将 base64 图像垂直拆分为多个图像或您建议的任何更好的解决方法。

注意:这个答案解决了我遇到的同样问题,但我无法理解逻辑。

4

0 回答 0