我试图在 opencv 中扭曲图像。起初,由于 cv::undistort(raw, undist, cameraMatrix, distCoeffs);
可以正常工作,用针孔相机拍摄的图像没有失真。现在,我正在尝试使用我在此处找到的补丁将 undist
扭曲回其原始状态:http://code.opencv.org/issues/1387
但到目前为止,我还没有设法让它发挥作用。这是代码:
void distort(const cv::Mat& src, cv::Mat& dst, const cv::Mat& cameraMatrix, const cv::Mat& distCoeffs)
{
cv::Mat pixel_locations_src = cv::Mat(src.size(), CV_32FC2);
for (int i = 0; i < src.size().height; i++) {
for (int j = 0; j < src.size().width; j++) {
pixel_locations_src.at<cv::Point2f>(i,j) = cv::Point2f(j,i);
}
}
cv::Mat fractional_locations_dst = cv::Mat(src.size(), CV_32FC2);
cv::Mat pixel_locations_dst = cv::Mat(src.size(), CV_32FC2);
cv::undistortPoints(pixel_locations_src, pixel_locations_dst, cameraMatrix, distCoeffs);
const float fx = cameraMatrix.at<double>(0,0);
const float fy = cameraMatrix.at<double>(1,1);
const float cx = cameraMatrix.at<double>(0,2);
const float cy = cameraMatrix.at<double>(1,2);
// is there a faster way to do this?
for (int i = 0; i < fractional_locations_dst.size().height; i++) {
for (int j = 0; j < fractional_locations_dst.size().width; j++) {
const float x = fractional_locations_dst.at<cv::Point2f>(i,j).x*fx + cx;
const float y = fractional_locations_dst.at<cv::Point2f>(i,j).y*fy + cy;
pixel_locations_dst.at<cv::Point2f>(i,j) = cv::Point2f(x,y);
}
}
cv::remap(src, dst, pixel_locations_dst, cv::Mat(), CV_INTER_LINEAR);
}
我试图将 RGB 图像传递给该函数,但由于 undistortPoints
采用 1*N、2 channel 矩阵,代码将在 undistortPoints
处触发断言,我不知道不明白为什么 distort()
将 1xN 矩阵作为输入。
任何有关该主题的信息都会很棒。谢谢
最佳答案
我最终采用了不同的方法,我只需要扭曲回特定的一组点,代码如下:
void DistortPoints(const std::vector<cv::Point2f> & src, std::vector<cv::Point2f> & dst, const cv::Mat& cameraMatrix, const cv::Mat& distorsionMatrix)
{
double fx = cameraMatrix.at<double>(0,0);
double fy = cameraMatrix.at<double>(1,1);
double cx = cameraMatrix.at<double>(0,2);
double cy = cameraMatrix.at<double>(1,2);
std::vector<cv::Point3f> src2;
for (int i = 0; i < src.size(); i++)
src2.push_back(cv::Point3f((src[i].x - cx) / fx, (src[i].y - cy) / fy, 0));
cv::Mat rVec(3, 1, cv::DataType<double>::type, cv::Scalar(0)); // Rotation vector
cv::Mat tVec(3, 1, cv::DataType<double>::type, cv::Scalar(0)); // Translation vector
std::vector<cv::Point2f> dst2;
cv::projectPoints(src2, rVec, tVec, cameraMatrix, distorsionMatrix, dst);
}
关于c++ - 不能在opencv C++中扭曲背面图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34612337/