PyQt5實(shí)現(xiàn)將Matplotlib圖像嵌入到Scoll Area中顯示滾動(dòng)條效果
如題目所述,又是花費(fèi)了兩天的時(shí)間實(shí)現(xiàn)了該功能,本來(lái)今天下午有些心灰意冷,打算放棄嵌入到Scoll Area中的想法,但最后還是心里一緊,仔細(xì)梳理了一下邏輯,最終實(shí)現(xiàn)了功能
效果展示

注意:當(dāng)你想實(shí)現(xiàn)一個(gè)子功能的時(shí)候,可以從新創(chuàng)建兩個(gè)文件:
×××.ui文件(如上圖效果展示是和我項(xiàng)目里的位置一樣的)×××.py文件(用來(lái)實(shí)現(xiàn)功能)
截圖

如上圖所示,
紅色框里的文件是實(shí)現(xiàn)效果展示的所有源文件。但是文件夾testcode是為了實(shí)現(xiàn)將Matplotlib圖像嵌入到Scoll Area中所做的所有工作,稍后我會(huì)將參考資源放入文章末尾
一、解決步驟
1.1 qt designer
設(shè)計(jì)ui文件,控件的位置需要和自己項(xiàng)目中控件的位置相同,以便功能實(shí)現(xiàn)后方便項(xiàng)目調(diào)用

保存為
testpiv.ui文件
1.2 pycharm編寫(xiě)程序
直加看代碼不懂得話,建議查看1.3中的參考文章,我實(shí)現(xiàn)該功能也是來(lái)源于這些
代碼
import cv2
import os
import sys
import math
from PyQt5 import QtCore
from PyQt5.QtWidgets import *
from PyQt5.uic import loadUi
import matplotlib
from matplotlib import pyplot as plt
matplotlib.use("Qt5Agg") # 聲明使用QT5
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
matplotlib.use("Qt5Agg") # 聲明使用QT5
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
#創(chuàng)建一個(gè)matplotlib圖形繪制類(lèi)
class MyFigure(FigureCanvas):
def __init__(self,width, height, dpi):
# 創(chuàng)建一個(gè)Figure,該Figure為matplotlib下的Figure,不是matplotlib.pyplot下面的Figure
self.fig = plt.figure(figsize=(width, height), dpi=dpi)
# 在父類(lèi)中激活Figure窗口,此句必不可少,否則不能顯示圖形
super(MyFigure,self).__init__(self.fig)
# 調(diào)用Figure下面的add_subplot方法,類(lèi)似于matplotlib.pyplot下面的subplot(1,1,1)方法
class scollarea_showpic(QMainWindow):
def __init__(self, queryPath=None, samplePath=None,limit_value = None):
super().__init__()
self.queryPath = queryPath # 圖庫(kù)路徑
self.samplePath = samplePath # 樣本圖片
self.limit_value = limit_value
self.ui()
plt.rcParams['font.sans-serif'] = ['KaiTi'] # 只有這樣中文字體才可以顯示
def ui(self):
loadUi('./testpiv.ui', self)
self.SIFT(self.queryPath,self.samplePath,self.limit_value)
def getMatchNum(self,matches,ratio):
'''返回特征點(diǎn)匹配數(shù)量和匹配掩碼'''
matchesMask=[[0,0] for i in range(len(matches))]
matchNum=0
for i,(m,n) in enumerate(matches):
if m.distance < ratio * n.distance: #將距離比率小于ratio的匹配點(diǎn)刪選出來(lái)
matchesMask[i]=[1,0]
matchNum+=1
return (matchNum,matchesMask)
def SIFT(self,dirpath,picpath,limit_value):
# path='F:/python/gradu_design/gra_des/'
queryPath=dirpath #圖庫(kù)路徑
samplePath=picpath #樣本圖片
comparisonImageList=[] #記錄比較結(jié)果
#創(chuàng)建SIFT特征提取器
sift = cv2.xfeatures2d.SIFT_create()
#創(chuàng)建FLANN匹配對(duì)象
"""
FLANN是類(lèi)似最近鄰的快速匹配庫(kù)
它會(huì)根據(jù)數(shù)據(jù)本身選擇最合適的算法來(lái)處理數(shù)據(jù)
比其他搜索算法快10倍
"""
FLANN_INDEX_KDTREE=0
indexParams=dict(algorithm=FLANN_INDEX_KDTREE,trees=5)
searchParams=dict(checks=50)
flann=cv2.FlannBasedMatcher(indexParams,searchParams)
sampleImage=cv2.imread(samplePath,0)
kp1, des1 = sift.detectAndCompute(sampleImage, None) #提取樣本圖片的特征
for parent,dirnames,filenames in os.walk(queryPath):
print('parent :',parent,'','dirnames :',dirnames)
for p in filenames:
p=queryPath+p
# print('pic file name :',p)
queryImage=cv2.imread(p,0)
kp2, des2 = sift.detectAndCompute(queryImage, None) #提取比對(duì)圖片的特征
matches=flann.knnMatch(des1,des2,k=2) #匹配特征點(diǎn),為了刪選匹配點(diǎn),指定k為2,這樣對(duì)樣本圖的每個(gè)特征點(diǎn),返回兩個(gè)匹配
(matchNum,matchesMask) = self.getMatchNum(matches,0.9) #通過(guò)比率條件,計(jì)算出匹配程度
matchRatio=matchNum*100/len(matches)
drawParams=dict(matchColor=(0,255,0),singlePointColor=(255,0,0),matchesMask=matchesMask,flags=0)
comparisonImage=cv2.drawMatchesKnn(sampleImage,kp1,queryImage,kp2,matches,None,**drawParams)
comparisonImageList.append((comparisonImage,matchRatio)) #記錄下結(jié)果
comparisonImageList.sort(key=lambda x:x[1],reverse=True) #按照匹配度排序 降序
new_comparisonImageList = comparisonImageList[:limit_value]
count=len(new_comparisonImageList)
column = 1 # 列
row = math.ceil(count/column) # 行math.ceil: 函數(shù)返回大于或等于一個(gè)給定數(shù)字的最小整數(shù)
print('列:',column, ' ','行:',row)
#繪圖顯示
F = MyFigure(width=10, height=10, dpi=100) # 500 * 400
for index,(image,ratio) in enumerate(new_comparisonImageList):
F.axes = F.fig.add_subplot(row,column,index+1)
F.axes.set_title('Similiarity %.2f%%' % ratio)
plt.imshow(image)
# 調(diào)整subplot之間的間隙大小
plt.subplots_adjust(hspace=0.2)
self.figure = F.fig
# FigureCanvas:畫(huà)布
self.canvas = FigureCanvas(self.figure) # fig 有 canvas
self.canvas.resize(self.picwidget.width(), 3000) # 畫(huà)布大小
self.scrollArea = QScrollArea(self.picwidget) # picwidget上有scroll
self.scrollArea.setFixedSize(self.picwidget.width(), self.picwidget.height())
self.scrollArea.setWidget(self.canvas) # widget上有scrollscroll有canvas
self.nav = NavigationToolbar(self.canvas, self.picwidget) # 創(chuàng)建工具欄
self.setMinimumSize(self.width(), self.height())
self.setMaximumSize(self.width(), self.height())
self.setWindowTitle('Test')
if __name__ == "__main__":
app = QApplication(sys.argv)
queryPath='F:/python/gradu_design/gra_des/imges/' #圖庫(kù)路徑
samplePath='F:/python/gradu_design/gra_des/imges/resized_logo1_1.jpg' #樣本圖片
main = scollarea_showpic(queryPath,samplePath,3)
main.show()
sys.exit(app.exec_())
下載地址
源碼下載:test_scollarea.py
總結(jié)
從目前我的認(rèn)知來(lái)講,你想要實(shí)現(xiàn)的功能,基本上換一種思路、想法,都是可能會(huì)有解決方案的,只不過(guò)可能難度不同,你需要投入的精力不同。
結(jié)合本篇博客來(lái)說(shuō),從我產(chǎn)生這個(gè)想法來(lái)說(shuō),我一直在找資料,從一開(kāi)始的簡(jiǎn)單搜索同一個(gè)內(nèi)容到后面轉(zhuǎn)變搜索思路,到最后梳理邏輯框架、代碼,最后實(shí)現(xiàn)功能,此過(guò)程耗費(fèi)的時(shí)間(兩天多)不算長(zhǎng),但也不算短。中間的過(guò)程是煎熬的,幾次試圖想放棄,最后還是挺了過(guò)來(lái),還是很開(kāi)心的。
只要不放棄,你就可以!
以上就是PyQt5實(shí)現(xiàn)將Matplotlib圖像嵌入到Scoll Area中顯示滾動(dòng)條效果的詳細(xì)內(nèi)容,更多關(guān)于PyQt5 Matplotlib圖像嵌入的資料請(qǐng)關(guān)注本站其它相關(guān)文章!
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信