I am not sure whether this is you want exactly. But have a look on the following code. It creates horizontal and vertical histograms of a thresholded image. What it actually does is simply count all nonzero pixels and store in a Mat object with respect to X or Y coordinate.
Mat gray;
Mat ret;
cvtColor(img,gray,CV_BGR2GRAY);
imshow("Gray Image",gray);
threshold(gray,ret,0,255,CV_THRESH_BINARY_INV+CV_THRESH_OTSU);
Mat horizontal(ret.cols,1,CV_32S);
horizontal = Scalar::all(0);
Mat vertical(ret.rows,1,CV_32S);
vertical = Scalar::all(0);
for(int i=0;i<ret.cols;i++)
{
horizontal.at<int>(i,0)=countNonZero(ret(Rect(i,0,1,ret.rows)));
}
for(int i=0;i<ret.rows;i++)
{
vertical.at<int>(i,0) = countNonZero(ret(Rect(0,i,ret.cols,1)));
}