一. 效果
输入图片:test.jpg
前向场:test.npy
输出图片:dewarp_img.jpg
二. 代码
import os
import cv2
import numpy as npdef align_flow(image, flow):"""flow: -1~1, 非文本区域是nanbm_flow: 对齐的bm,可以直接对图片进行remap操作"""img_w, img_h = image.shape[1], image.shape[0]bm_flow = flow / 2 + 0.5bm_flow[..., 0] = bm_flow[..., 0] * img_wbm_flow[..., 1] = bm_flow[..., 1] * img_hbm_flow = cv2.resize(bm_flow, (img_w, img_h))return bm_flowdef dewarp(img_path, bm_path):img = cv2.imread(img_path)flow = np.load(bm_path)bm_flow = align_flow(img, flow)dewarp_img = cv2.remap(img, bm_flow.astype(np.float32), None, cv2.INTER_LINEAR, borderValue=(255, 255, 255))return dewarp_imgif __name__ == "__main__":img_path = "test.jpg"bm_path = "test.npy"dewarp_img = dewarp(img_path, bm_path)cv2.imwrite("dewarp_img.jpg", dewarp_img)
注:cv2.remap() 函数的作用是把img,通过bm_flow映射成新的图片
img: height, width, 3
bm_flow: height, width, 2
dewarp_img: height, width, 3
如何理解?
bm_flow其实就是一个映射,把原始图像上每个像素点映射到新的图片中。
单步调试发现:
img[100, 100, :] = [113, 116, 120]
bm_flow[100,100,:] = [70:111]
dewarp_img[70, 111, :] = [113, 116, 120]