將同樣的一張圖(101*156),采用兩種不同的方式進行縮放填充,帶來的像素差異:
1.先填充后縮放
def resize_1(img):
height, width, channel = img.shape
temp = np.zeros((height,height,3),np.uint8)
start = (height -width) / 2
temp[:,start:width+start,:] = img
img1 = cv2.resize(temp,(300,300))
cv2.imwrite('test_1.jpg',img1)
return img1
2.先縮放后填充
def resize_1(img):
height, width, channel = img.shape
temp = np.zeros((height,height,3),np.uint8)
start = (height -width) / 2
temp[:,start:width+start,:] = img
img1 = cv2.resize(temp,(300,300))
cv2.imwrite('test_1.jpg',img1)
return img1
opencv2默認采用的是INTER_LINEAR(雙線性插值法)
3.對比兩張圖片的不同並且可視化
def compare(img1,img2,img3):
count = 0
height,width,channel = img1.shape
for h in xrange(height):
for w in xrange(width):
if sum(img1[h][w]) != sum(img2[h][w]):
print(img1[h][w])
print(img2[h][w])
count += 1
img3[h][w] = [0,0,255]
# pass
print(count)
cv2.imwrite('test.jpg',img3)
結果將會顯示近一半的像素值不同.
為什么會產生這種原因呢?
主要是坐標的位置發生了變化,因為我們采用的opencv默認的是雙線性插值:
SrcX=(dstX+0.5)* (srcWidth/dstWidth) -0.5
SrcY=(dstY+0.5) * (srcHeight/dstHeight)-0.5
則假設我們src圖像為100*150,縮放到200*300,然后最終填充到300*300,
所以要找dst(0,30)對應的src坐標,(四舍五入)
srcx = 0.5 * 0.5 - 0.5 = 0
srcy = 30.5*0.5 -0.5 = 15
但是第一種擴大的方式找到的(0,15)是基於前面帶有黑邊的坐標,而第二種方式是沒有帶黑邊的坐標,
由於坐標的偏移,最終導致了縮放最后肉眼看着沒有什么區別,但是對於圖像的像素來說已經有近一半的不同。