Matplotlib从一个充满1的数组中生成黑色图像 [英] Matplotlib produces a black image from an array full of ones

查看:269
本文介绍了Matplotlib从一个充满1的数组中生成黑色图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简介

我正在使用 matplotlib.pyplot 进行一些测试。当我试图保存人工图像时,我遇到了一种奇怪的行为。这是我为保存图像而创建的非常简单的函数:

I am doing some tests with matplotlib.pyplot. When I tried to save artificial images, I encoutered a strange behavior. Here is the very simple function I created to save images :

import numpy as np
import matplotlib
import matplotlib.pyplot as plt

def save_image(array, name):

    array = array*255.
    fig = plt.figure()
    plt.imsave(name, array.astype('uint8'), cmap=matplotlib.cm.gray)
    plt.close(fig)

return 0

问题

当我尝试创建一个带有零的数组的图像时,我得到一个黑暗的图像,正如预期的那样:

When I try to create an image with an array full of zeros, I get a dark image, as expected :

zeros_array = np.zeros((200,200), dtype='float')
save_image(zeros_array, 'Dark.jpg')

但是,当我尝试创建时一个带有数组的图像,我仍然得到一个黑暗的图像:

However, when I try to create an image with an array full of ones, I still get a dark image :

ones_array = np.ones((200,200), dtype='float')
save_image(ones_array, 'White.jpg')

< a href =https://i.stack.imgur.com/CICX1.jpg =nofollow noreferrer>

有趣的是,当我创建一个 mixed_array ,对于不同强度的正方形,现在充满1的区域显示为白色:

Interestingly enough, when I create a mixed_array, with squares of different intensities, the regions full of ones now appear as white :

mixed_array = np.ones((200,200), dtype='float')
mixed_array[:100,:100] = 0.25
mixed_array[100:,100:] = 0.75
save_image(mixed_array, 'Mixed.jpg')

问题:

有谁知道为什么 matplotlib 拒绝保存完整的白色图像,但图像中的白色区域没有问题吗?

Does anyone know why matplotlib refuses to save a full white image but has no problem with white regions in an image?

我可能遗漏了一些非常明显或基本的东西,但我看不清楚。

I am probably missing something very obvious or fundamental but I cannot see what.

推荐答案

我想你要设置 vmin vmax 当你打电话给 imsave 。如果不这样做,它将自动从阵列中确定。来自文档

I think you want to set the vmin and vmax when you call imsave. If you don't, it will be automatically determined from the array. From the docs:


vmin / vmax:[无|标量]

vmin/vmax: [ None | scalar]

vmin和vmax通过固定映射到色彩图颜色限制的值来设置图像的颜色缩放比例。如果vmin或vmax为None,则该限制由arr min / max值确定。

vmin and vmax set the color scaling for the image by fixing the values that map to the colormap color limits. If either vmin or vmax is None, that limit is determined from the arr min/max value.

因此,请尝试将您的函数更改为:

So, try changing your function to:

def save_image(array, name):

    array = array*255.
    fig = plt.figure()
    plt.imsave(name, array.astype('uint8'), cmap=matplotlib.cm.gray, vmin=0, vmax=255)
    plt.close(fig)

这篇关于Matplotlib从一个充满1的数组中生成黑色图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆