本文介绍了将OpenCV重映射代码从C ++转换为python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将c ++ opencv cv2.remap代码转换为python.我没有收到任何错误,但结果与预期不符.我正在放大图像
I am trying to convert c++ opencv cv2.remap code to python. I am not getting any error but result is not as expected.I am getting zoomed image
c ++代码
int main()
{
Mat img = imread("captcha1.jpg");
float phase = -0.8 * CV_PI;
float omega = 2.0 * CV_PI / img.cols;
float amp = 15;
Mat_<Vec2f> proj(img.size());
for (int y=0; y<img.rows; y++) {
for (int x=0; x<img.cols; x++) {
float u = 0;
float v = sin(phase + float(x) * omega) * amp;
proj(y,x) = Vec2f(float(x) + u, float(y) + v);
}
}
Mat corr;
cv::remap(img, corr, proj, cv::Mat(), INTER_LINEAR);
imshow("in",img);
imshow("out",corr);
waitKey();
}
python代码:
from __future__ import print_function
import cv2
import numpy as np
from past.builtins import xrange
def update():
for j in xrange(rows):
for i in xrange(cols):
phase = -0.8 * np.pi
omega = 2.0 * np.pi / cols
amp = 15
u = -100
v = np.sin(phase + float(i) * omega) * amp
value_xy = (float(i) + u) + (float(j) + v)
map_x.itemset((j, i), value_xy)
map_y.itemset((j, i), 0)
img = cv2.imread('test.jpg')
map_x = np.zeros(img.size, np.float32)
map_y = np.zeros(img.shape[:2], np.float32)
rows, cols = img.shape[:2]
update()
dst = cv2.remap(img, map_x, map_y, cv2.INTER_LINEAR)
cv2.imshow('dst', dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
原始图片:
C ++结果:
Python结果:
推荐答案
这是我的结果:
通常,在Python中,我更喜欢the vectorized implementation
而不是the for-loop implementation
.这是我的代码:
Generaly, I prefer the the vectorized implementation
to the for-loop implementation
in Python. Here is my code:
#!/usr/bin/python3
# 2018.09.23 12:24 (CST)
import cv2
import numpy as np
fname = "remap.jpg"
img = cv2.imread(fname)
nh, nw = img.shape[:2]
PI = 3.141592653589793
phase = -0.8 * PI
omega = 2.0 * PI / nw
amp = 15
xs, ys = np.meshgrid(np.arange(0, nw), np.arange(0, nh))
ys = np.sin(phase+xs*omega)*amp + ys
xs = np.float32(xs)
ys = np.float32(ys)
dst= cv2.remap(img, xs, ys, cv2.INTER_CUBIC)
cv2.imwrite("dst.png", dst)
这篇关于将OpenCV重映射代码从C ++转换为python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!