将numpy数组转换为图像

时间:2015-03-02 21:17:30

标签: python arrays numpy jpeg

我有一个代表jpg的numpy数组,而不是文件。因此我必须直接处理数组。我想将这些数据保存到文件中,以便我可以使用常用的jpg查看器进行观看。通常我可以用

来做到这一点
pl = pylab.imshow(ds.pixel_array, cmap=pylab.cm.bone)

但是图像信息是在jpg2000中编码的,因此这种方法失败了。我试过pgmagick:

tmp = pgmagick.Image(ds.pixel_array)
logging.info("Info I")
pl = pgmagick.Blob()
tmp.write(pl, 'GRAY')

但不幸的是,这也失败了,numpy-array无法转换为pgmagick-image的错误。有没有其他方法将jpg2000编码的信息转换为PIL-able信息?

更新:
运行以下行

jpg_bytes = ds.pixel_array.astype('uint8').tostring()

导致以下错误:

Data type not understood by NumPy: format='uint12', PixelRepresentation=0, BitsAllocated=12

编辑:完整的功能:

def convert(self, inputpic, outputpic = "", force = False):
        if not inputpic or not os.path.isfile(inputpic):
            logging.critical("No valid input filename entered, or input file not found. Input filename was " + inputpic)
            return INT_ERROR
        else:
            input_clean = self.cleanEnding(inputpic)
            if not outputpic:
                outputpic = input_clean + ".jpg"
            print "Output pic is " + outputpic
            if os.path.isfile(outputpic + ".jpg") and force is False:
                logging.critical("Output file is already there, don't want to overwrite it! Output filename was " + outputpic)
            else:
                if outputpic[:-4] is not ".jpg":
                    outputpic = outputpic + ".jpg"
                try:
                    ds = dicom.read_file(inputpic, force=True)
                except InvalidDicomError:
                    logging.critical("File " + inputpic + " is not a dicom file!")
                    return INT_ERROR
                #try:
                #    pl = pylab.imshow(ds.pixel_array, cmap=pylab.cm.bone)
                #except:
                try:
                    logging.info("Decoding starts now")
                    jpg_bytes = "".join(chr(x) for x in ds.pixel_array)
                    logging.info("Test I")
                    jpg_bytes = ds.pixel_array.astype('uint8').tostring()
                    logging.warning("Trying to decode it with pgmagick")
                    im = pgmagick.Image.open(io.BytesIO(jpg_bytes))
                    logging.info("Decoding successfull")
                    #logging.info("Info I")
                    #pl = pgmagick.Blob()
                    #tmp.write(pl, 'GRAY')
                except Exception as e:
                    logging.critical("Critical error happened during imshow() with file " + inputpic + " with the following error: " + str(e))
                    return INT_ERROR
                if not os.path.isfile("tmp.png"):
                    pylab.savefig("tmp.png")
                else:
                    logging.critical("tmp.png is already in this folder, maybe a failed cleanup? Stopping!")
                    return INT_ERROR
                im = Image.open("tmp.png")
                bg = Image.new("RGB", im.size, (255,255,255))
                bg.paste(im, (0,0), im)
                bg.save(outputpic[:-4], quality=95)
                os.remove("tmp.png")
        return INT_SUCCESS

使用inputpic作为dicom文件。 日志记录文件中的错误在第一个logging.info(logging.info("Decoding starts now"))之后出现,因此我假设在第三行不再出现在日志文件中之后,从第二行抛出错误。

1 个答案:

答案 0 :(得分:2)

假设pixel_array是一个字节数组,表示JPEG编码的图像(如果是这种情况,则前四个字节 - 幻数 - 将为FF D8 FF E0。)

您可以使用以下方法将numpy数组转换为字节字符串:

jpg_bytes = ds.pixel_array.astype('uint8').tostring()

您可以使用以下命令加载字节字符串:

import io
from pgmagick import Image

im = Image.open(io.BytesIO(jpg_bytes))

编辑:我错过了“jpg2000”位,所以:

  • pgmagick可以加载jpg2000文件,上面的代码可以正常运行。
  • jpg2000文件的幻数是0000 000C 6A50 2020 0D0A 870A