使用双线性插值缩放图像

待我称王封你为后i 2022-10-08 00:59 304阅读 0赞

双线性插值原理解析

  1. import numpy as np
  2. import cv2
  3. def main(src, dst, src_w, src_h, dst_w, dst_h, scale_x, scale_y):
  4. for n in range(3): # 对channel循环
  5. for dst_y in range(dst_h): # 对height循环
  6. for dst_x in range(dst_w): # 对width循环
  7. # 目标在源上的坐标
  8. src_x = (dst_x + 0.5) * scale_x - 0.5
  9. src_y = (dst_y + 0.5) * scale_y - 0.5
  10. # 计算在源图上四个近邻点的位置
  11. src_x_0 = int(np.floor(src_x))
  12. src_y_0 = int(np.floor(src_y))
  13. src_x_1 = min(src_x_0 + 1, src_w - 1)
  14. src_y_1 = min(src_y_0 + 1, src_h - 1)
  15. # 双线性插值
  16. value0 = (src_x_1 - src_x) * src[src_y_0, src_x_0, n] + (src_x - src_x_0) * src[src_y_0, src_x_1, n]
  17. value1 = (src_x_1 - src_x) * src[src_y_1, src_x_0, n] + (src_x - src_x_0) * src[src_y_1, src_x_1, n]
  18. dst[dst_y, dst_x, n] = int((src_y_1 - src_y) * value0 + (src_y - src_y_0) * value1)
  19. return dst
  20. if __name__ == '__main__':
  21. img = cv2.imread('scaleTest.jpg')
  22. src_h, src_w, channel = img.shape
  23. dst_h, dst_w = 1920, 1080
  24. dst = np.zeros((dst_h, dst_w, 3),np.uint8)
  25. args = (img, dst, src_w, src_h, dst_w, dst_h, src_w / dst_w, src_h / dst_h)
  26. dst = main(*args)
  27. cv2.namedWindow('dd', cv2.WINDOW_NORMAL)
  28. print(dst)
  29. cv2.imshow('dd',dst)
  30. cv2.waitKey(0)
  31. cv2.imwrite('bie.jpg', dst)
  32. cv2.destroyAllWindows()
  33. # import numpy as np
  34. # import cv2
  35. # from matplotlib import pyplot as plt
  36. #
  37. # img_path = 'scaleTest.jpg'
  38. # img = cv2.imread(img_path)
  39. # src_h = img.shape[0]
  40. # src_w = img.shape[1]
  41. # dst_h = int(1.8 * src_h) # 图像缩放倍数
  42. # dst_w = int(1.8 * src_w) # 图像缩放倍数
  43. #
  44. # dst_img = np.zeros((dst_h, dst_w, 3), dtype=np.uint8)
  45. # for c in range(3):
  46. # for h in range(dst_h):
  47. # for w in range(dst_w):
  48. # # 目标点在原图上的位置
  49. # # 使几何中心点重合
  50. # src_x = (w + 0.5) * src_w / dst_w - 0.5
  51. # src_y = (h + 0.5) * src_h / dst_h - 0.5
  52. # if src_x < 0:
  53. # src_x = 0
  54. # if src_y < 0:
  55. # src_y = 0
  56. # # 不考虑几何中心重合直接对应
  57. # # src_x = w*src_w/dst_w
  58. # # src_y = h*src_h/dst_h
  59. #
  60. # # 确定最近的四个点
  61. # # np.floor()返回不大于输入参数的最大整数。(向下取整)
  62. # x1 = int(np.floor(src_x))
  63. # y1 = int(np.floor(src_y))
  64. # x2 = int(min(x1 + 1, src_w - 1)) # 防止超出原图像范围
  65. # y2 = int(min(y1 + 1, src_h - 1.6))
  66. #
  67. # # x方向线性插值,原公式本来要除一个(x2-x1),这里x2-x1=1
  68. # R1 = (x2 - src_x) * img[y1, x1, c] + (src_x - x1) * img[y1, x2, c]
  69. # R2 = (x2 - src_x) * img[y2, x1, c] + (src_x - x1) * img[y2, x2, c]
  70. #
  71. # # y方向线性插值,同样,原公式本来要除一个(y2-y1),这里y2-y1=1
  72. # P = (y2 - src_y) * R1 + (src_y - y1) * R2
  73. # dst_img[h, w, c] = P
  74. # plt.imshow(dst_img)

发表评论

表情:
评论列表 (有 0 条评论,304人围观)

还没有评论,来说两句吧...

相关阅读