Python:将二进制数组显示为图像

时间:2018-11-26 08:32:32

标签: python

我有一个遮罩图像,从技术上讲,它是一个充满True / False值的矩阵。我想将其视为图像。首先,我用({astype(np.uint8)

将其转换为二进制数组
print('Part Mask', p['masks'][class_id].astype(np.uint8))

但是我仍然无法在Python笔记本下将其视为图像。 OpenCV发疯并崩溃了内核。

有人知道如何在Python笔记本上查看这样的结构而不损坏内核吗?

    [[0 0 0 ... 0 0 0]
     [0 0 0 ... 0 0 0]
     [0 0 0 ... 0 0 0]
     ...
     [0 0 0 ... 0 0 0]
     [0 0 0 ... 0 0 0]
     [0 0 0 ... 0 0 0]]

否则也可以():

[[False False False ... False False False]
 [False False False ... False False False]
 [False False False ... False False False]
 ...
 [False False False ... False False False]
 [False False False ... False False False]
 [False False False ... False False False]]

谢谢。

编辑:我无法在此处复制粘贴整个代码,但基本上我有一个预测张量p,而p[masks][class_id]是我要可视化的对象(显示每个类的遮罩)。

enumerator = 0
# run through the instances
for class_id in p['class_ids']:
    #print('Image:', image) # the original input image
    #print('Mask:', merged_mask) # whole masked image
    print('ID: ', class_names[class_id] + str(enumerator))
    #print('Outline Poses: ', ) # mask boundary coordinates
    #print('Pose:',) # mask center coordinates
    print('Part Mask', p['masks'][class_id].astype(np.uint8)) # how to visualize this as an image?
    print('Confidence: ', p['scores'][class_id])
    print('BB: ', p['rois'][class_id]) # get the BB
    print('--------------------------')
    enumerator = enumerator + 1

enter image description here

PS:Matplotlib也不起作用。这是我尝试打印时得到的图像:

enter image description here

2 个答案:

答案 0 :(得分:0)

Matplotlib应该为您工作:

import numpy as np
from matplotlib import pyplot as plt


image = np.eye(10)
binary = image > 0
plt.imshow(binary)
plt.show()

结果:

enter image description here

修改:
您的图片的形状为(510,7),您得到的正是您所期望的:

import numpy as np
from matplotlib import pyplot as plt


image = np.eye(510)[:,:7]
binary = image > 0
plt.imshow(binary)
plt.show()

结果:
enter image description here

答案 1 :(得分:0)

也许您可以使用PIL

from PIL import Image

data = [...]

width = len(data[0])
height = len(data)

output_image = Image.new(mode='1', size=(width, height))

for x in range(height):
    for y in range(width):
        pixel_value = data[x][y]
        output_image.putpixel((x,y), pixel_value)


output_image

数据= [[0,0,0,0],[0,0,1,1],[1,1,1,0],[0,1,1,0]]

我有这样的图片-> Click and zoom image to pixels