使用坐标垫(OpenCV/C ++)访问图像值 [英] Access to image values using a Mat of coordinates (OpenCV/C++)

查看:92
本文介绍了使用坐标垫(OpenCV/C ++)访问图像值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在openCV(C ++)中,我有一幅图像 IMG ,我想提取存储在 coor 中的位置处每个像素的值.是否有可能以有效的方式获得此像素值? foor循环(使用 .at(i,j))是否有效?是否有内置函数可以执行此操作? 这是我的代码:

In openCV(C++) I have an image IMG and I'd like to extract the values of each pixel at positions store in coor. Is it possible to get this pixel values in an efficient way? Is a foor loop (using .at(i,j)) efficient ?Is there a built-in function for doing this? This is my code:

cv::Mat IMG = cv::imread("image.png",CV_LOAD_IMAGE_GRAYSCALE);
cv::Mat coor = (cv::Mat_<float>(3,2) << 1, 0, 0, 1, 2, 2); // search coordinates
cv::Mat pixel_values;
// and I'd like to do something like this:
//This should result in a matrix with the same size as *coor*
pixel_values = IMG.at(coor); // similar to the matrix accesing method in Matlab. 

推荐答案

Threr是访问cv :: Mat中像素"值的不同方法.您阅读过OpenCV的文档吗?

Threr are different ways to access the value of a "pixel" in a cv::Mat. Have you read the documentation of OpenCV?

我建议您从此处

修改 我已经更正了代码:此代码可用于msvc 2015和opencv(3.1),但> 2也可以

Edit I've corrected the code: this code works with msvc 2015 and opencv (3.1) but also > 2 is ok

#include <iostream>
#include <vector>
#include <opencv2/opencv.hpp>
#include <cstdint>
using namespace std;

#if defined(NDEBUG)
#pragma comment(lib, "opencv_world310.lib")
#else
#pragma comment(lib, "opencv_world310d.lib")
#endif // 


cv::Mat GetPixelsFromMat( const cv::Mat& I, const std::vector<cv::Point2f>& points )
{
    // some pre-condition:
    cv::Mat res( 1, (int)points.size( ), CV_8UC1 );

    int i = 0;
    for( const auto& point : points )
        res.ptr( 0 )[ i++ ] = I.at<uchar>( cvRound( point.y ), cvRound( point.x ) );

    return res;
}

int main( int argc, char* argv[] )
{
    cv::Mat testImg( 1, 10, CV_8UC1 );
    for( int i = 0; i < 10; ++i )
        testImg.ptr( 0 )[ i ] = i;

    std::vector<cv::Point2f> points;
    points.push_back( cv::Point2f( 1, 0 ) );
    points.push_back( cv::Point2f( 5, 0 ) );
    points.push_back( cv::Point2f( 9, 0 ) );

    cv::Mat pixelsMap = GetPixelsFromMat( testImg, points );

    if( pixelsMap.ptr( 0 )[ 0 ] == 1 )
        cout << "OK 0" << endl;
    else
        cout << "FAIL 0" << endl;

    if( pixelsMap.ptr( 0 )[ 1 ] == 5 )
        cout << "OK 1" << endl;
    else
        cout << "FAIL 1" << endl;

    if( pixelsMap.ptr( 0 )[ 2 ] == 9 )
        cout << "OK 2" << endl;
    else
        cout << "FAIL 2";


    return EXIT_SUCCESS;
}

这是一个很大的简化,但我认为这是一个起点.

This is a big semplification but I think it's a starting point.

这篇关于使用坐标垫(OpenCV/C ++)访问图像值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆