在pyplot中添加图像会降低其分辨率吗? [英] Does adding images in pyplot lowers their 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").
produces the output seen below on the left. On the right, is the original image ('sampleimage.jpg') which I imported in the code.
分辨率上的差异很明显.有没有办法在保持质量的前提下将图像添加到地块?
The difference in resolution is apparent. Is there a way to add images to plots, whilst retaining their quality?
推荐答案
在问题代码中,OffsetImage
被赋予了参数zoom=0.9
.这意味着原始图像的每个像素在屏幕上占0.9/0.72 = 1.25像素.因此,原始图像的5个像素需要在屏幕上压缩为4个像素.这不可避免地会导致在代码输出中观察到一些伪像.
In the code from the question the OffsetImage
is given an argument zoom=0.9
. This means that each pixel of the original image takes 0.9/0.72=1.25 pixels on screen. Hence 5 pixels of the original image needs to squeezed into 4 pixels on screen. This inevitably leads to some artifacts as observed in the output of the code.
如果要求以原始图像的精确分辨率显示图像,则需要确保OffsetImage
每像素恰好使用一个像素.这可以通过将缩放比例设置为ppi为72.除以数字dpi(默认为100)来实现.
If the requirement is to show the image in the exact resolution of the original image, you need to make sure to use exactly one pixel per pixel for the OffsetImage
. This would be accomplished by setting the zoom to the ppi of 72. divided by the figure dpi (100 by default).
OffsetImage(arr_img, zoom=72./self.figure.dpi)
结果,显示的图像在matplotlib图中确实具有与原始图像相同的尺寸.
As a result, the image shown would indeed have the same dimensions in the matplotlib plot as the original image.
这篇关于在pyplot中添加图像会降低其分辨率吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!