在matplotlib上的循环中,仅将图形中的图像保存为png,且尺寸相同

2024-09-28 19:34:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我在计算机视觉领域工作,我试图将微软的Coco数据集转换成png图像,这样我就可以直接在Caffe上使用它们了。在

我修改了他们API的一些函数,这样我就有了正确的分割颜色(每个类id在rgb中有(id,id,id)颜色,背景是(0,0,0))。以下是修改后的函数:

def showAnns(self, anns):
    """
    Display the specified annotations.
    :param anns (array of object): annotations to display
    :return: None
    """
    if len(anns) == 0:
        return 0
    if 'segmentation' in anns[0]:
        datasetType = 'instances'
    elif 'caption' in anns[0]:
        datasetType = 'captions'
    if datasetType == 'instances':
        ax = plt.gca()
        polygons = []
        color = []
        # sort annotations from biggest to smallest to avoid occlusions
        anns.sort(key=lambda x: x['area'], reverse=True)

        for ann in anns:

            pixelvalue = ann['category_id']/255.0
            c = [pixelvalue, pixelvalue, pixelvalue]
            if type(ann['segmentation']) == list:
                # polygon
                for seg in ann['segmentation']:
                    poly = np.array(seg).reshape((len(seg)/2, 2))
                    polygons.append(Polygon(poly, True,alpha=1))
                    color.append(c)
            else:
                # mask
                t = self.imgs[ann['image_id']]
                if type(ann['segmentation']['counts']) == list:
                    rle = mask.frPyObjects([ann['segmentation']], t['height'], t['width'])
                else:
                    rle = [ann['segmentation']]
                m = mask.decode(rle)
                img = np.ones( (m.shape[0], m.shape[1], 3) )
                color_mask = c
                for i in range(3):
                    img[:,:,i] = color_mask[i]
                ax.imshow(np.dstack( (img, m*0.5) ))

        p = PatchCollection(polygons, facecolors=color, edgecolors=(1,1,1,1), linewidths=1, alpha=1)
        ax.add_collection(p)
    elif datasetType == 'captions':
        for ann in anns:
            print ann['caption']

下面的python脚本中调用了以下代码:

^{pr2}$

所以我的问题是:当我这样做的时候,我得到了一个大小与原来不同的保存png。我希望有完全相同的维度,因为这对评估很重要:任何错位的像素都会降低深度学习阶段的准确性。在

我还没有找到一个适当的方法来保存图形的“图像”部分,去掉了图形中的任何其他东西。假设我有一个640*480的图像输入,我希望有与输出相同的大小。在

谢谢你的阅读


Tags: toin图像idforifmaskax
1条回答
网友
1楼 · 发布于 2024-09-28 19:34:31

使用计数器,并将其附加到路径字符串:

COUNT = 0

for img in imgs:

    # load and display image
    I = io.imread('%s/images/%s/%s'%(dataDir,dataType,img['file_name']))
    # 0 all values for black background
    I[:] = 0
    plt.imshow(I)
    # load and display instance annotations
    annIds = coco.getAnnIds(imgIds=img['id'], catIds=catIds, iscrowd=None)
    anns = coco.loadAnns(annIds)
    coco.showAnns(anns)
    print img['file_name']
    #path='vocstyle_cocoimages/'+str(img['file_name'])[:-4]+'.png'
    #your new line
    path='vocstyle_cocoimages/'+str(img['file_name'])[:-4]+ '_' + str(COUNT) + '.png'
    plt.savefig(path, bbox_inches='tight', pad_inches=0)
    #increment counter
    COUNT = COUNT + 1

相关问题 更多 >