OpenCV读取RGB值。每次运行的值不一致

时间:2018-12-01 01:03:36

标签: c++ opencv

使用相同的图像和蒙版运行此代码时,有时会得到以前不同的值。例如

Normal/Expected Results

Abnormal Results

从两个结果中可以看出,我以某种方式接收到负RGB值。对于具有完全相同的蒙版的完全相同的图像,大约每5到8次运行都会显示异常结果。

为了防止偶尔出现异常结果,我需要更改什么?

#include <opencv2/opencv.hpp>
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <string>

using namespace cv;
using namespace std;

float get_color(Mat img,Mat &mask){
    Mat img1 = img;
    Mat hist;
    int dims = 1;
    int histSize = 255;
    float hranges[] = { 0, 255 };
    const float *ranges = {hranges};

    calcHist(&img1,1,0,mask,hist, dims, &histSize, &ranges ,true ,false);

    int sum=0;
    for(int i = 0;i<256;i++){
        sum += hist.at<float>(i,0);
    }
    Mat weights = hist/sum;
    float hist_avg=0.0;
    for(int i = 0;i<256;i++){
        hist_avg += i*weights.at<float>(i,0);
    }
    return hist_avg;
}

int main(int argc, char** argv){
    Mat aa = imread("/Users/dnguyen/Desktop/snapshot207042/pic.jpg", CV_LOAD_IMAGE_COLOR);
    vector<Mat> bgr;
    split(aa, bgr);
    Mat b = bgr[0];
    Mat g = bgr[1];
    Mat r = bgr[2];
    for(unsigned int i=1;i<23;i++){
        stringstream ss;
        ss << i;
        string str = ss.str();
        string file_name =     "/Users/dnguyen/Desktop/okay/data/card_masks/"+str+"_mask.png";
        Mat mask = imread(file_name,0);
        Mat cc;
        threshold(mask,cc,90,255,THRESH_BINARY);

        float b_avg = get_color(b, cc);
        float g_avg = get_color(g, cc);
        float r_avg = get_color(r, cc);

        cout  << b_avg << ","<< g_avg << "," << r_avg << endl;
    }
}

0 个答案:

没有答案