Matplotlib是一個(gè)優(yōu)秀的繪圖庫,用于在開發(fā)中颂鸿,驗(yàn)證數(shù)據(jù)。然而攒庵,在MacOS + PyCharm的開發(fā)環(huán)境中嘴纺,存在有一些問題,其中包括:
- backend
- imshow浓冒,opencv
- int or float
- jupyter
- _tkinter
backend
驗(yàn)證Matplotlib的配置文件.matplotlib/matplotlibrc
栽渴,將backend項(xiàng)修改為TkAgg,如下:
backend : TkAgg
或者稳懒,在Python文件中闲擦,直接指定,如下:
import matplotlib
matplotlib.use('TkAgg')
imshow
在PyCharm中场梆,調(diào)用Matplotlib的imshow()顯示圖像佛致,需要額外使用pylab的show(),否則無法顯示辙谜,如下:
import matplotlib.pyplot as plt
image = cv2.imread(img_path)
plt.imshow(image)
pylab.show()
由于OpenCV讀取圖像的通道是BGR俺榆,而Matplotlib的通道是RGB,需要轉(zhuǎn)換装哆,調(diào)用cv2.cvtColor()罐脊,如下:
image = cv2.imread(img_path)
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
pylab.show()
int or float
Matplotlib顯示圖像定嗓,如果是01區(qū)間,值為float萍桌,如果是0255區(qū)間宵溅,值為int,需要轉(zhuǎn)換上炎,否則無法顯示恃逻,空白圖像,報(bào)錯(cuò):
Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).
轉(zhuǎn)換數(shù)據(jù)格式藕施,調(diào)用astype()即可寇损,如下:
image = cv2.imread(img_path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image = img_to_array(image)
image = image.astype(int) # 0~255轉(zhuǎn)換為int
plt.imshow(image)
pylab.show()
jupyter
Jupyter是可交互的web端開發(fā)工具,Matplotlib也可集成在其中裳食,需要添加%matplotlib inline
矛市,激活內(nèi)置的Matplotlib,如下:
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
No module named '_tkinter'
Matplotlib在Ubuntu服務(wù)器上诲祸,可能導(dǎo)致的問題浊吏,找不到_tkinter
,錯(cuò)誤如下:
ImportError: No module named '_tkinter', please install the python3-tk package
安裝python3-tk包救氯,即可:
sudo apt-get install python3-tk
That's all! Enjoy it!