在 Visual Studio 2019 上使用带有 C++ 的 OpenCV 对图片的每一列进行颜色平均

Take the color avarage of each column of a picture using OpenCV with C++ on Visual Studio 2019

我是 C++ 新手,需要计算每列中红色的平均值。随后,我需要制作每列颜色密度级别的图表。

这是我使用的图片,是骨密度测量的样本:

到目前为止,这是我的代码:

#include <opencv2/opencv.hpp>
#include <string>
#include <vector>
#include <iostream>
#include <windows.h>

using namespace cv;
using namespace std;

int main(int argc, char** argv) {

FARPROC pGetPixel;

std::cout << "Medidas de muestra 1: \n";
Mat img = imread("C:\Users\Jimena G. Gordillo\OneDrive\Pictures\den.bmp");

int matriz = img.cols * img.rows * 3;
const size_t chanels = 3; //RGB

//Lectura de cada pixel
for (int x = 0; x < img.cols; x++) {
    for (int y = 0; y < img.rows; y++) {
    
        size_t p = y * img.cols * chanels + x * chanels; //
        uchar b = img.data[p + 0];
        uchar g = img.data[p + 1];
        uchar r = img.data[p + 2];

        for (int i = 0; i <= img.cols; i++) { //here is where I want to obtain the sum of each column
            int sum = sum + i;
        //Calculate average 
        long long average = sum / img.rows; // average is divided by the total of rows
        }
    }
}

cout << "Filas: " << img.rows<< endl;
cout << "Columnas: " << img.cols << endl;
cout << "Area: " << matriz << endl;

namedWindow("imagen", WINDOW_AUTOSIZE);
imshow("imagen", img);

waitKey(); 
return 0;

}

感谢任何帮助。

您正在尝试逐行检查而不是逐列检查,也不需要第三个 for 循环

这是每个通道(红色、绿色、蓝色)列平均值的解和每个通道的列平均值图。

来源:

每列平均值的红色通道图:

每列平均值的绿色通道图:

每列平均值的蓝色通道图:

代码:

#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>

using namespace cv;
using namespace std;

int main()
{
    Mat img = imread("/ur/source/image/directory/img.png");
    
    imshow("Source",img);
    
    long int avgRedChannel = 0,avgGreenChannel = 0, avgBlueChannel = 0;
    
    Mat graphRedChannel = Mat::zeros(Size(img.cols,300),CV_8UC1);
    Mat graphGreenChannel = Mat::zeros(Size(img.cols,300),CV_8UC1);
    Mat graphBlueChannel = Mat::zeros(Size(img.cols,300),CV_8UC1);
    
    
    for(int i=0;i<img.cols;i++)
    {
        for(int j=0;j<img.rows;j++)
        {
            avgBlueChannel += (int)img.at<Vec3b>(Point(i,j))[0];
            avgGreenChannel += (int)img.at<Vec3b>(Point(i,j))[1];
            avgRedChannel += (int)img.at<Vec3b>(Point(i,j))[2];
        }
        graphBlueChannel.at<uchar>(Point(i,(avgBlueChannel/img.rows))) = 255;
        graphGreenChannel.at<uchar>(Point(i,(avgGreenChannel/img.rows))) = 255;
        graphRedChannel.at<uchar>(Point(i,(avgRedChannel/img.rows))) = 255;
        avgBlueChannel = 0;
        avgGreenChannel = 0;
        avgRedChannel = 0;
    }
    
    imshow("RedChannelGraph",graphRedChannel);
    imshow("GreenChannelGraph",graphGreenChannel);
    imshow("BlueChannelGraph",graphBlueChannel);
                        
    waitKey(0);
    return(0);
}