OpenCV直方图计算,以及颜色迁移

本文的前两个代码主要是来自于书本《OPenCV计算机视觉编程攻略》最后一个代码是根据前两个代码做的一个颜色迁移

黑白图片的直方图计算

//
//  main.cpp
//  TextureFusion2
//
//  Created by coriander on 10/14/17.
//  Copyright © 2017 xiaowoCorp. All rights reserved.
//

#include 
#include 
#include 
#include 
//
//filename format
//r11 r12 r13
//r21 r22 r23
//r31 r32 r33
//t1 t2 t3
/

using namespace std;
class Histogram1D{
private:
    int histSize[1];//直方图中箱子的数目
    float hranges[2];
    const float*ranges[1];
    int channels[1];
public:
    Histogram1D(){
        histSize[0]=256;
        hranges[0]=0.0;
        hranges[1]=256;
        ranges[0]=hranges;
        channels[0]=0;
    }
    cv::Mat getHistogram(const  cv::Mat& image){
        cv::Mat hist;
        cv::calcHist(&image, 1, channels, cv::Mat(), hist, 1, histSize, ranges);
        return  hist;
    }
    cv::Mat getHistogramImage(const cv::Mat &image,int zoom=1){
        cv::Mat hist=getHistogram(image);
        return getImageOfHistogram(hist,zoom);
    }
    static cv::Mat getImageOfHistogram(const cv::Mat &hist,int zoom){
        double maxVal=0;
        double minVal=0;
        cv::minMaxLoc(hist, &minVal, &maxVal,0,0);
        int histSize=hist.rows;
        cv::Mat histImg(histSize*zoom,histSize*zoom,CV_8U,cv::Scalar(255));
        int hpt=static_cast<int>(0.9*histSize);
        for(int h=0;hfloat binVal=hist.at<float>(h);
            if(binVal >0){
                int intensity=static_cast<int >(binVal*hpt/maxVal);
                cv::line(histImg, cv::Point(h*zoom,histSize*zoom), cv::Point(h*zoom,(histSize-intensity)*zoom), cv::Scalar(0),zoom);

            }

        }
        return histImg;
    }
};
int main(){
    cv::Mat image1=cv::imread("Mesh0.jpg",0);
    Histogram1D h;
    cv::Mat histo=h.getHistogram(image1);

    for(int i=0;i<256;i++)
        cout<<"value"<"="<float>(i)<"Histgram");
    cv::imshow("Histgram", h.getHistogramImage(image1));


    cv::waitKey();

    return 0;
}

OpenCV直方图计算,以及颜色迁移_第1张图片

你可能感兴趣的:(计算机视觉,opencv)