从字节数组中读取未压缩的图像
Read uncompressed image from byte array
我从超声波设备创建了一个未压缩的 dicom 视频。现在我想在 python 应用程序中逐帧阅读它并暂时保存文件。稍后我想添加一些图像处理。到目前为止,我已经尝试提取属于第一帧的字节。
import dicom
import array
from PIL import Image
filename = 'image.dcm'
img = dicom.read_file(filename)
byte_array = array.array('B', img.PixelData[0:(img.Rows * img.Columns)])
现在如何将这个字节数组放入文件(位图、jpeg 等等)?我尝试将 python 图片库与 image = Image.fromarray(byte_array)
一起使用,但出现错误。
AttributeError: 'str' object has no attribute 'array_interface'
我想在某个地方我还必须指定图像的尺寸,但还没有弄清楚如何。
感谢评论,我找到了解决方法。 Image 在 'RGB' 中,数组的形状是 (3L, 800L, 376L)。我可以将 pixel_array
作为 numpy 数组并将其重塑为 (800L, 376L, 3L),而不是将其转换为字节数组。
import dicom
from PIL import Image
filename = 'image.dcm'
img = dicom.read_file(filename)
output = img.pixel_array.reshape((img.Rows, img.Columns, 3))
image = Image.fromarray(output).convert('LA')
image.save('output.png')
我从超声波设备创建了一个未压缩的 dicom 视频。现在我想在 python 应用程序中逐帧阅读它并暂时保存文件。稍后我想添加一些图像处理。到目前为止,我已经尝试提取属于第一帧的字节。
import dicom
import array
from PIL import Image
filename = 'image.dcm'
img = dicom.read_file(filename)
byte_array = array.array('B', img.PixelData[0:(img.Rows * img.Columns)])
现在如何将这个字节数组放入文件(位图、jpeg 等等)?我尝试将 python 图片库与 image = Image.fromarray(byte_array)
一起使用,但出现错误。
AttributeError: 'str' object has no attribute 'array_interface'
我想在某个地方我还必须指定图像的尺寸,但还没有弄清楚如何。
感谢评论,我找到了解决方法。 Image 在 'RGB' 中,数组的形状是 (3L, 800L, 376L)。我可以将 pixel_array
作为 numpy 数组并将其重塑为 (800L, 376L, 3L),而不是将其转换为字节数组。
import dicom
from PIL import Image
filename = 'image.dcm'
img = dicom.read_file(filename)
output = img.pixel_array.reshape((img.Rows, img.Columns, 3))
image = Image.fromarray(output).convert('LA')
image.save('output.png')