自研OpenCV warpAffine平移实现与官方结果不符,求排查问题
自研warpAffine平移实现与OpenCV官方结果不一致的问题排查
因业务需求,需基于GPU重实现OpenCV的warpAffine,且仅需支持图像平移操作,对应的2×3变换矩阵形式为:
[[ 1, 0, x_shift], [ 0, 1, y_shift]]
为验证算法正确性,先编写了Python原型实现,核心代码如下:
import math import numpy as np # Bilinear Interpolation: # for a source image, sample a value indexed by (y, x) even if x, y are fractionals. def sample(img, x: float, y: float): h, w = img.shape left = math.floor(x) top = math.floor(y) right = left + 1 bottom = top + 1 # top left corner if (0 <= left < w) and (0 <= top < h): a = img[top, left] else: a = 0 # top right corner if (0 <= right < w) and (0 <= top < h): b = img[top, right] else: b = 0 # bottom left corner if (0 <= left < w) and (0 <= bottom < h): c = img[bottom, left] else: c = 0 # bottom right corner if (0 <= right < w) and (0 <= bottom < h): d = img[bottom, right] else: d = 0 # linear interpolation of top two points top_interleaved = (right - x) * a + (x - left) * b # linear interpolation of bottom two points bottom_interleaved = (right - x) * c + (x - left) * d # linear interpolation of top and bottom points return (bottom - y) * top_interleaved + (y - top) * bottom_interleaved def warpAffine(img, shift_x: float, shift_y: float): output = np.empty_like(img) h, w = img.shape for y in range(h): for x in range(w): output[y, x] = sample(img, x - shift_x, y - shift_y) return output
测试用例与自研实现输出
a = np.arange(1, 5, dtype=np.float32).reshape(2, 2) # a = [[1, 2], # [3, 4]] shift_x = 0.1 shift_y = 0.1 warpAffine(a, shift_x, shift_y)
输出结果:
array([[0.81, 1.71], [2.52, 3.7 ]], dtype=float32)
OpenCV官方测试与输出
import cv2 as cv affine_arr = np.array([[1, 0, shift_x], [0, 1, shift_y]], dtype=np.float32) affine_img = cv.warpAffine( a, affine_arr, (a.shape[1], a.shape[0]), flags=cv.INTER_LINEAR, borderMode=cv.BORDER_CONSTANT, borderValue=0, )
输出结果:
array([[0.82, 1.73], [2.55, 3.72]], dtype=np.float32)
已研读OpenCV warpAffine源码但仍未能定位问题,恳请熟悉该函数的开发者帮忙排查自研实现的问题。
内容的提问来源于stack exchange,提问作者Shuai
相关产品推荐
相关产品推荐

