将同样的一张图(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)是基于前面带有黑边的坐标,而第二种方式是没有带黑边的坐标,
由于坐标的偏移,最终导致了缩放最后肉眼看着没有什么区别,但是对于图像的像素来说已经有近一半的不同。