在pyplot中添加图像是否会降低其分辨率?

时间:2018-02-06 09:17:42

标签: python image matplotlib plot resolution

以下代码

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

import sys

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

from matplotlib.offsetbox import OffsetImage, AnnotationBbox

import matplotlib.pyplot as plt
import numpy as np

class View(QGraphicsView):

    def __init__(self):
        super(View, self).__init__()

        self.initScene(5)

    def initScene(self,h):     

        self.scene = QGraphicsScene()
        self.figure = plt.figure()
        self.canvas = FigureCanvas(self.figure)
        self.figure.subplots_adjust(left=0.03,right=1,bottom=.1,top=1,wspace=0, hspace=0)

        ax = self.figure.add_subplot(111)
        ax.set_xlim([0,1000])
        data = np.random.rand(1000)
        ax.plot(data, '-') 

        arr_img = plt.imread('sampleimage.jpg',format='jpg')
        im = OffsetImage(arr_img,zoom=.9)

        ab = AnnotationBbox(im, (.5, .5), xycoords='axes fraction')
        ax.add_artist(ab)

        self.canvas.draw()
        self.setScene(self.scene)
        self.scene.addWidget(self.canvas)

class MainWindow(QMainWindow):

    def __init__(self):
        super(MainWindow,self).__init__()

        #self.setGeometry(150, 150, 700, 550) 

        self.view = View()
        self.setCentralWidget(self.view)

app = QApplication(sys.argv)

window = MainWindow()
window.show()

app.exec_()

生成左下方的输出。在右侧,是我在代码中导入的原始图像(' sampleimage.jpg')。

enter image description here

分辨率的差异很明显。有没有办法将图像添加到图中,同时保留其质量?

1 个答案:

答案 0 :(得分:1)

在问题的代码中,OffsetImage被赋予参数zoom=0.9。这意味着原始图像的每个像素在屏幕上占据0.9 / 0.72 = 1.25像素。因此,原始图像的5个像素需要在屏幕上挤压成4个像素。这不可避免地导致在代码输出中观察到的一些伪像。

如果要求以原始图像的精确分辨率显示图像,则需要确保OffsetImage每像素只使用一个像素。这可以通过将缩放设置为72的ppi来实现。除以图dpi(默认为100)。

OffsetImage(arr_img, zoom=72./self.figure.dpi)

因此,所显示的图像在matplotlib图中的确具有与原始图像相同的尺寸。

enter image description here