Binarization and Accessing Pixels

When you want to measure the amount of root of plants, one solution is measureing the area of root in a image of root. Here, you can view the method of binarization and countiong black pixels of the binarized image. At firtst, converts the image to gray scale by cvtColor function. Then it it will be binarized by the threshold function. Then we will continue to access to each pixel and get a number of black pixels. Finally, output the number of black pixels.

root root_bin

Source Code

This source code is protected by the GNU GPL license. Please visit here for the terms of the GNU GPL license.

//
//  area
//
//  Copyright 2015 Yuki Mochizuki
//

#include <iostream>
#include <stdio.h>
#include "opencv/cv.h"
#include "opencv/highgui.h"
#include <cmath>

using namespace std;
using namespace cv;



int main()
{
    Mat src_img = imread("/Users/YM/Desktop/root.jpg");

    Mat gray_img;
    cvtColor(src_img, gray_img, CV_BGR2GRAY);
    
    Mat bin_img;
    threshold(gray_img, bin_img, 0, 255, THRESH_BINARY|THRESH_OTSU);
    
    cvNamedWindow("src", CV_WINDOW_AUTOSIZE);
    cvNamedWindow("gray", CV_WINDOW_AUTOSIZE);
    cvNamedWindow("bin", CV_WINDOW_AUTOSIZE);
    
    cv::imshow("src", src_img);
    cv::imshow("gray", gray_img);
    cv::imshow("bin", bin_img);
    
    int s=0;
    
    for(int y = 0; y < bin_img.rows; ++y){
        for(int x = 0; x < bin_img.cols; ++x){
            for(int c = 0; c < bin_img.channels(); ++c){
                if(bin_img.data[ y * bin_img.step + x * bin_img.elemSize() + c ]==0)s++;
            }
        }
    }
    
    cout<<s<<" pixel/ "<<bin_img.rows*bin_img.cols<<" pixel ("<<(double)s/bin_img.rows/bin_img.cols*100<<" %)"<<endl;
    cvWaitKey(0);
}