本系列博客主要分享Python在機器視覺/計算機視覺下的編程應用
cv2包是著名的視覺庫OpenCV的Python實現
在求峰值信噪比PSNR時,我們需要求取目標圖像和實際圖像之間的誤差。
err = abs(imgsrc-imgobj)
opencv 提供了一個便捷的函數cv2.absdiff
來獲取誤差。
import cv2
import numpy as np
img = cv2.imread('img.jpg')
imgd = cv2.resize(img,(img.shape[1]/4,img.shape[0]/4)) #先下采樣4倍再上采樣恢復圖像
imgu = cv2.resize(imgd,(img.shape[1],img.shape[0]))
err = cv2.absdiff(img,imgu) #差值的絕對值
cv2.imshow('img',img)
cv2.imshow('imgd',imgd)
cv2.imshow('imgu',imgu)
cv2.imshow('err',err)
cv2.waitKey()
cv2.destroyAllWindows()
我們可以用matplotlib來顯示一下結果
import matplotlib.pyplot as plt
fig = plt.figure('result')
plt.axis('off') #關閉坐標軸
plt.subplot(2,2,1) #將窗口分為兩行兩列四個子圖,則可顯示四幅圖片
plt.title('imgsrc') #第一幅圖片標題
plt.imshow(img)
plt.subplot(2,2,2)
plt.title('imgdownsample')
plt.imshow(imgd)
plt.subplot(2,2,3)
plt.title('imgupsampling')
plt.imshow(imgu)
plt.subplot(2,2,4)
plt.title('imgerr')
plt.imshow(err)
fig.tight_layout()#調整整體空白
plt.subplots_adjust(wspace =0)#調整子圖間距
plt.show() #顯示
需要注意的是,如果使用圖像矩陣直接相減再求絕對值,會得到錯誤的結果:
```python
import cv2
import numpy as np
img = cv2.imread('img.jpg')
imgd = cv2.resize(img,(img.shape[1]/4,img.shape[0]/4)) #先下采樣4倍再上采樣恢復圖像
imgu = cv2.resize(imgd,(img.shape[1],img.shape[0]))
err = cv2.absdiff(img,imgu) #差值的絕對值
err1 = np.abs(img - imgu) #差值
errdiff =err-err1
print(err1.mean())
#>>> 108.2134 #兩種方法計算的誤差不一樣!!!!
這主要是由於圖像中的元素為numpy.array,其數據類型為uint8,無符號導致負數不能夠正確表示
type(err1[0,0,0])>>>numpy.uint8
為了解決這個問題,需要在讀入數據的時候對圖像進行數據類型轉換:
import cv2
import numpy as np
img = cv2.imread('img.jpg').astype(np.int16)
''' np.float32變為np.int32/int16也可以, int32可以保存-2147483648~214748364 int16可以保存-32768~32767, int16類似於CV_16SC1 int32類似於CV_32SC1'''
imgd = cv2.resize(img,(img.shape[1]/4,img.shape[0]/4)) #先下采樣4倍再上采樣恢復圖像
imgu = cv2.resize(imgd,(img.shape[1],img.shape[0]))
err = cv2.absdiff(img,imgu) #差值的絕對值
err1 = np.abs(img - imgu) #差值
errdiff =err-err1
print(errdiff.mean())
#>>>0.0 #這時結果就相同了
要求取兩幅圖像差值,建議使用cv2.absdiff(img1,img2)
pic from pexels.com
ref:
datatype:http://blog.sina.com.cn/s/blog_662c7859010105za.html
datatype:https://blog.csdn.net/liu13364876993/article/details/83538095
abs sign:https://blog.csdn.net/u012494876/article/details/80629474
img:https://www.pexels.com/photo/black-chimpanzee-smiling-50582/
matplot write:https://blog.csdn.net/GAN_player/article/details/78543643
https://blog.csdn.net/jifaley/article/details/79687000
http://www.cnblogs.com/nju2014/p/5620776.html
cmap:
https://matplotlib.org/users/colormaps.html
https://matplotlib.org/xkcd/examples/color/colormaps_reference.html TODO
http://pyhogs.github.io/colormap-examples.html
psnr:
http://www.cnblogs.com/tiandsp/archive/2012/11/14/2770462.html
https://blog.csdn.net/szfhy/article/details/49615833