首页 > 解决方案 > 以良好的分辨率将 JPG 图像添加到 Matplotlib 绘图

问题描述

我正在尝试将 JPEG 图像添加到 Python 图中,并且图像看起来非常像素化。

我以前在图像分辨率方面遇到过问题(请参阅我在这里提出的上一个问题)。我通常遵循此处给出的答案,并且效果很好。出于某种原因,这一次我无法以相同的分辨率将图像插入到绘图中。

这是我的代码:

import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
import seaborn as sns

class Figure():
    def __init__(self, ColumnWidth, AspectRatio):
        InchesPerPoint = 1.0/72.27
        FigWidth       = ColumnWidth * InchesPerPoint
        FigHeight      = FigWidth*AspectRatio
        self.FigSize   = [FigWidth, FigHeight]
        
    def UpdateParameters(self):
        params = {'backend': 'ps',
          'figure.facecolor':'white',
          'axes.facecolor':'white',
          'axes.labelsize': 8,
          'legend.fontsize': 8,
          'xtick.labelsize': 8,
          'ytick.labelsize': 8,
          'text.usetex': False,
          'font.family': 'serif',
          'figure.figsize': self.FigSize}

        plt.rcParams.update(params)

    def ProduceFigureAxes(self):
        self.fig = plt.figure() 
        self.L=0.13
        self.B=0.17
        self.W=.5-self.L
        self.H=.97-self.B

    def AddAxes(self):
        ax = self.fig.add_axes([self.L, self.B, self.W, self.H]) 
        return ax

    def AddDataToAxes(self, ax):
        
        x = [1, 2, 3, 4]
        y = [1, 2, 3, 4]
        
        ax.plot(x, y, "-o")
        ax.set_xlabel("X")
        ax.set_ylabel("Y")
        
    def AddImage(self):
        ax = self.fig.add_axes([self.W + self.L, self.B, self.W, self.H]) 
        sns.despine(ax=ax, top = True, left = True, right = True, bottom = True)
        ax.set_xticks([])
        ax.set_yticks([])
        
        # load the image
        im  = Image.open('./TEST.jpg')
        [a, b] = im.size
        im  = im.resize((int(a/10.0), int(b/10.0)), Image.ANTIALIAS)
        im  = np.asarray(im)
        im = OffsetImage(im, zoom = 72.0/self.fig.dpi)
        im.image.axes = ax
        ab = AnnotationBbox(im, (.8, .5),  xycoords='axes fraction', bboxprops =dict(edgecolor='white', facecolor = 'white', alpha = 0.01))
        ax.add_artist(ab)
        
    def SaveFigure(self, FILENAME):
        plt.savefig(FILENAME+'.png', facecolor=self.fig.get_facecolor())
    

# parameters of the figure    
ColumnWidth = 255.22124 # in points
GoldenMean  = (np.sqrt(5)-1.0)/2.0 # aspect ratio
Fig = Figure(ColumnWidth, GoldenMean)
Fig.UpdateParameters()
Fig.ProduceFigureAxes()
ax = Fig.AddAxes()
Fig.AddDataToAxes(ax)
Fig.AddImage()
Fig.SaveFigure("TEST")

这是我要插入的图像(分辨率 1024x1024): 在此处输入图像描述

这是最终结果: 在此处输入图像描述

如果有人对为什么图像看起来如此像素化有任何建议,我将不胜感激。谢谢!

标签: pythonimagematplotlibpython-imaging-library

解决方案


推荐阅读