我正在使用matplotlib和PIL库创建不同形状的二进制图像(即,只有黑白,没有其他 colored颜色 ).我对像素数的限制是64x64,图像必须是二进制的.在这个较低的像素范围内,我得到的像素化图像如下所示.我正在寻找一种方法,在这种方法中,我可以最大限度地减少白色像素的突出,使它们的变化更加均匀和渐进.

Magnified image with 64x64 pixels

我使用了以下代码来生成此图像.

import matplotlib.pyplot as plt
import numpy as np
import io
from PIL import Image

def get_image_array(_fig):
    io_buffer = io.BytesIO()
    plt.savefig(io_buffer, format="raw")
    io_buffer.seek(0)
    _image_array = np.reshape(
        np.frombuffer(io_buffer.getvalue(), dtype=np.uint8),
        newshape=(int(_fig.bbox.bounds[3]), int(_fig.bbox.bounds[2]), -1)
    )
    io_buffer.close()
    return _image_array

def draw_box_and_circle(bbox, xc, yc, r, pixels=(100, 100), angular_parts=100):
    fig = plt.figure(figsize=(pixels[0]*0.01, pixels[1]*0.01))
    fig.add_axes(plt.Axes(fig, [0., 0., 1., 1.]))
    # draw bbox
    x0, y0, x1, y1 = bbox
    plt.fill([x0, x1, x1, x0], [y0, y0, y1, y1], color='0')
    # draw circle
    theta = np.linspace(0.0, 2.0*np.pi, angular_parts)
    x = xc + (r*np.cos(theta))
    y = yc + (r*np.sin(theta))
    plt.fill(x, y, color='1')
    #
    plt.axis('off')
    plt.axis('equal')
    plt.xlim([BBOX[0], BBOX[2]])
    plt.ylim([BBOX[1], BBOX[3]])
    image_array = get_image_array(fig)
    print(image_array.shape)
    image = Image.fromarray(image_array)
    image.save("before_conversion.png")
    image = image.convert(mode="1")
    image.save("after_conversion.png")
    print(np.array(image).shape)    
    return
   

BBOX = (0.0, 0.0, 1.0, 1.0)
draw_box_and_circle(BBOX, 0.5, 0.5, 0.25)

推荐答案

您可能希望在从RGB转换时禁用抖动,请使用:

image = image.convert(mode="1", dither=0)

您还可以考虑直接生成一个二进制形状,而不是从Matplotlib"阈值"消除锯齿形状.

例如,使用类似以下内容:

xc = 0.5
yc = 0.5
r = 0.25

n_pixels = 100
dxy = 1/n_pixels
hdxy = dxy/2

yy, xx = np.mgrid[hdxy:1-hdxy:dxy, hdxy:1-hdxy:dxy]

# subtract the center
xx = xx - xc
yy = yy - yc

# treshold distance from center to create 
# the (binary) circle
circle = np.sqrt(xx**2 + yy**2) <= r
circle = (circle*255).astype(np.uint8)

并用plt.imshow(circle, resample="nearest")来绘制array.它可能会让您在像素级别进行更精细的控制.依赖Matplotlibs反走样可能会使您的解决方案后端特定?

enter image description here

Python相关问答推荐

aiohTTP与pytest的奇怪行为

Pandas基于另一列的价值的新列

Python:根据创建时间合并两个收件箱

使用pandas MultiIndex进行不连续 Select

零填充2D数组上的Numpy切片

取相框中一列的第二位数字

将词典写入Excel

使用Python进行网页抓取,没有页面

在Docker中运行HAProxy时无法获得503服务

Altair -箱形图边界设置为黑色,中线设置为红色

如何知道标志是否由用户传递或具有默认值?

收件箱转换错误- polars.exceptions. ComputeHelp- pandera(0.19.0b3)带有polars

理解Python的二分库:澄清bisect_left的使用

连接两个具有不同标题的收件箱

非常奇怪:tzLocal.get_Localzone()基于python3别名的不同输出?

未删除映射表的行

两个pandas的平均值按元素的结果串接元素.为什么?

如何使用pytest来查看Python中是否存在class attribution属性?

Python逻辑操作作为Pandas中的条件

无论输入分辨率如何,稳定扩散管道始终输出512 * 512张图像