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