Python中的双线性插值

时间:2017-08-06 17:04:56

标签: python opencv interpolation

我正在尝试评估通过实现最近邻和双线性插值来调整图像质量以调整图像大小。目前这两个图像看起来相同。我似乎无法找出双线性方法不能提供平滑输出图像的原因。以下是最近邻居

def scale_image_NN(image, scaling_factor):
    cv2.imshow('Original image', lena)
    cv2.waitKey(0)
    print 'Running'
    size = np.shape(image)
    scaled_image = np.zeros((size[0]*scaling_factor, size[1]*scaling_factor,3), dtype=np.uint32)
    for i in range (0, scaling_factor*size[0]-3):
         for j in range (0, scaling_factor*size[1]-3):
              x = int(m.floor(i/scaling_factor))
              y = int(m.floor(j/scaling_factor))
                   for k in range (0, 3):
                      scaled_image[i+1, j+1, k] = image[x+1, y+1, k]

    cv2.imshow('Scaled image - NN', scaled_image)
    cv2.waitKey(0)
cv2.imwrite('NN.jpg',scaled_image)

随后进行双线性插值

def scale_image_BL(image, scaling_factor):
    cv2.imshow('Original image', lena)
    cv2.waitKey(0)
    print 'Running'
    orig_size = np.shape(image)
    h = orig_size[0]
    w = orig_size[1]
    c = orig_size[2]
    r = scaling_factor 
    padded_image = np.zeros((h*scaling_factor, w*scaling_factor, c), dtype=np.uint8)

    for i in range (0, h*scaling_factor):
        x1 = int(m.floor(i/r))
        x2 = int(m.ceil(i/r))
        if x1 == 0:
            x1 = 1
       x = np.remainder(i/r,1)
       for j in range (0, w*scaling_factor):
            y1 = int(m.floor(j/r))
            y2 = int(m.ceil(j/r))
            if y1 == 0:
                y1 = 1
            ctl = image[x1, y1, :]
            cbl = image[x2, y1, :]
            ctr = image[x1, y2, :]
            cbr = image[x2, y2, :]      

            y = np.remainder(j/r, 1)
            tr = (ctr*y) + (ctl*(1-y))  
            br = (ctr*y) + (cbl*(1-y))
            padded_image[i, j, :] = (br*x)+(tr*(1-x))

    scaledImage = padded_image.astype(np.uint8)
    cv2.imshow('Scaled image - BL',scaledImage)
    cv2.waitKey(0)
    cv2.imwrite('BL.jpg',scaledImage)

1 个答案:

答案 0 :(得分:0)

问题是Why does Python return 0 for simple division calculation?

在计算两个位置之间进行插值时,比如在双线性插值中的x1或x2,python为简单除法(如1/2)而不是0.5而退回0,因此总是没有在两个点之间插值导致NN型输出。

要使scale_image_BL(image,scaling_factor)起作用,只需包含:

来自未来导入部门

在脚本的开头。