PokeLu
PokeLu

Reputation: 847

How to preserve the original image quality in matplotlib

I'm trying to do some modifications on the original images using matplotlib. Here's a replicable code:

fig, ax = plt.subplots(figsize=(7.68, 10.24))
img = matplotlib.image.imread(img_path)
ax.imshow(img)
plt.xticks([])
plt.yticks([])
plt.savefig('try.png')

But the image quality has degraded after this process even though it returns the same resolution. How to preserve the image quality when saving images?

Here are the examples: enter image description here enter image description here As you can see the scalars become unrecognizable after processing.

Upvotes: 0

Views: 381

Answers (1)

Diziet Asahi
Diziet Asahi

Reputation: 40667

You need to create an axes that takes the whole space available in the figure, as well as creating a figure with the right dimensions:

img = plt.imread('caOkv.jpg', format='JPG')
h,w,_ = img.shape
dpi = 100
fig = plt.figure(figsize=(w/dpi, h/dpi), dpi=dpi)
ax = fig.add_axes([0,0,1,1])
ax.axis('off')
ax.imshow(img)

Upvotes: 1

Related Questions