Getting black and white intensity values from a histogram - image-processing

I am trying to get black and white histogram data from a color image. However the current setup I have with my histogram only shows me color data I'm sure that it's something that I have to modify in my current math setup.
// Current setup on how to render histogram data to the screen with hist being the calculated histogram
histimg = Mat::zeros(200, 320, CV_8UC3)
int binW = histimg.cols / 16;
Mat buf(1, 16, CV_8UC3);
for( int i = 0; i < 16; i++ )
{
buf.at<Vec3b>(i) = Vec3b(saturate_cast<uchar>(i*180./16), 255, 255);
}
cvtColor(buf, buf, CV_HSV2BGR);
for( int i = 0; i < 16; i++ )
{
int val = saturate_cast<int>(hist.at<float>(i)*histimg.rows/255);
rectangle( histimg, Point(i*binW,histimg.rows),
Point((i+1)*binW,histimg.rows - val),
Scalar(buf.at<Vec3b>(i)), -1, 8 );
}
Thanks in advance for any advice.

Here are two methods:
Create whiteCount and blackCount variables. Iterate through all the pixels and increment whiteCount if the pixel is (255, 255, 255) and increment blackCount if the pixel is (0, 0, 0).
Convert the image to grayscale, create a histogram and look at the first and last bins.

Related

Detect areas corresponding to RGB

I have to create a program that takes a video as input
and after processing it has to be composed just from BGR colors.
Were red color is predominant it has to be (0,0,255),where blue is predominate (255,0,0) and for green (0,255,0).Every area where a color is predominant should have that color, not every pixel.
I found something but it works only for one color.
Mat redFilter(const Mat& src)
{
Mat redOnly;
inRange(src, Scalar(0, 0, 1), Scalar(100, 100, 255), redOnly);
}
Can you give me some ideas for this project?
You can set the pure blue, red or green color according to the highest among B,G,R values for each pixel.
Image:
Result:
Code:
#include <opencv2/opencv.hpp>
using namespace cv;
int main()
{
// Load image
Mat3b img = imread("D:\\SO\\img\\barns.jpg", IMREAD_COLOR);
// Result image with only pure B,G,R values
Mat3b bgr(img.size());
for (int r = 0; r < img.rows; ++r)
{
for (int c = 0; c < img.cols; ++c)
{
// Take highest among B,G,R
Vec3b v = img(r,c);
if (v[0] > v[1] && v[0] > v[2])
{
bgr(r, c) = Vec3b(255, 0, 0);
}
else if (v[1] > v[0] && v[1] > v[2])
{
bgr(r, c) = Vec3b(0, 255, 0);
}
else
{
bgr(r, c) = Vec3b(0, 0, 255);
}
}
}
imshow("Image", img);
imshow("Result", bgr);
waitKey();
return 0;
}
Here's something that you might be looking for. http://aishack.in/tutorials/tracking-colored-objects-opencv/
This article talks about segmenting objects of a specific color. You can use the same approach and identify images in red, green and blue. The article goes a step further and figures out "where" the object is as well.

OpenCV: Retrieving color of the center of a contour

Im trying to detect the colour of a set of shapes in a black image using OpenCV, for which I use Canny detection. However the color output always comes back as black.
std::vector<std::pair<cv::Point, cv::Vec3b> > Asteroids::DetectPoints(const cv::Mat &image)
{
cv::Mat imageGray;
cv::cvtColor( image, imageGray, CV_BGR2GRAY );
cv::threshold(imageGray, imageGray, 1, 255, cv::THRESH_BINARY);
cv::Mat canny_output;
std::vector<std::vector<cv::Point> > contours;
std::vector<cv::Vec4i> hierarchy;
int thresh = 10;
// Detect edges using canny
cv::Canny( imageGray, canny_output, thresh, thresh*2, 3 );
// Find contours
cv::findContours( canny_output, contours, hierarchy, CV_RETR_LIST, CV_CHAIN_APPROX_NONE, cv::Point(0, 0) );
std::vector<std::pair<cv::Point, cv::Vec3b> > points;
for(unsigned int i = 0; i < contours.size(); i++ )
{
cv::Rect rect = cv::boundingRect(contours[i]);
std::pair<cv::Point, cv::Vec3b> posColor;
posColor.first = cv::Point( rect.tl().x + (rect.size().width / 2), rect.tl().y + (rect.size().height / 2));
posColor.second = image.at<cv::Vec3b>( posColor.first.x, posColor.first.y );
//Dont add teh entry to the list if one with the same color and position is already pressent,
//The contour detection sometimes returns duplicates
bool isInList = false;
for(unsigned int j = 0; j < points.size(); j++)
if(points[j].first == posColor.first && points[j].second == posColor.second)
isInList = true;
if(!isInList)
points.push_back( posColor );
}
return points;
}
I know it has to be an issue with the positions or something along those lines, but I cant figure out what
I might be wrong, but off the top of my head :
Shouldn't this read
posColor.second = image.at<cv::Vec3b>(posColor.first.y, posColor.first.x);
and not the other way around like you did it ?
Matrix notation, not cartesian notation ?

Counting black pixels

I am using older version of C because the book I am using is outdated :( Currently, I am working on a project to detect an object in an image. First I do Gaussian smoothing on the gray scale image, then erode it. After that, I apply threshold. Now I am trying to obtain how many black pixels there are for every width so that I can compare it with other row to determine the center. I am trying this in 'for' loop, however, I am keep getting the error:
term does not evaluate to a function taking 1 arguments
#include <highgui.h>
#include <cv.h>
#include <cxcore.h>
int main()
{
int total,
zero,
width,
blackpixel;
IplImage* in = cvLoadImage("Wallet.jpg", CV_LOAD_IMAGE_GRAYSCALE);
IplImage* gsmooth = cvCreateImage(cvGetSize(in), IPL_DEPTH_8U, 1);
IplImage* erode = cvCreateImage(cvGetSize(in), IPL_DEPTH_8U, 1);
IplImage* Iat = cvCreateImage(cvGetSize(in), IPL_DEPTH_8U, 1);
IplImage* bpixel = cvCreateImage(cvGetSize(in), IPL_DEPTH_8U, 1);
cvSmooth(in, gsmooth, CV_GAUSSIAN, 3, 0, 0, 0);
cvErode(gsmooth, erode, NULL, 2);
cvThreshold(erode, Iat, 100, 255, CV_THRESH_BINARY);
total = (Iat->height)*(Iat->width);
zero = total - cvCountNonZero(Iat);
printf("Total pixels: %d\nWhite pixels: %d\nBlack pixels: %d\n", total, cvCountNonZero(Iat), zero);
for(int i = 0; i < Iat->width; i++)
{
blackpixel = Iat->width(i);
}
cvNamedWindow("Original", 1);
cvNamedWindow("Gaussian Smoothing", 1);
cvNamedWindow("Erode", 1);
cvNamedWindow("Adaptive Threshold", 1);
cvShowImage("Original", in);
cvShowImage("Gaussian Smoothing", gsmooth);
cvShowImage("Erode", erode);
cvShowImage("Adaptive Threshold", Iat);
cvWaitKey(0);
cvReleaseImage(&in);
cvReleaseImage(&gsmooth);
cvReleaseImage(&erode);
cvReleaseImage(&Iat);
cvDestroyWindow("Original");
cvDestroyWindow("Gaussian Smoothing");
cvDestroyWindow("Erode");
cvDestroyWindow("Adaptive Threshold");
}
First of all, don't be afraid to use C++ API when using an outdated book like "Learining OpenCV", because the concepts are still relevant. Translating to C++ API is not hard if You understand the idea, and is a great exercise because You can't just copy-paste the code. I learned OpenCV this way, and I think it worked :).
With C++ API it would be as simple as
cv::Mat zeros = cv::Mat::zeros(Iat.size());
cv::Mat blackPixels = (Iat == zeros);
int blackPixelsCount = blackPixels.total();
The problem in the line
blackpixel = Iat->width(i);
is the wrong syntax.
Iat->width will give you the width of the image, an integer property.
I don't thing that the loop
for(int i = 0; i < Iat->height; i++)
{
blackpixel = Iat->width(i);
}
can calculate the number of black pixels in a given row. You might need something like
for(int i = 0; i < Iat->height; i++) // // every row
{
for(int j = 0; j < Iat->width; j++) // pixels in each row
{
// get count pixels here
}
// do things with the count for the current row
}
If you are using a cvMat data structure instead of IplImage, this should be faster.

Can we use openCV to load and resize 2d image that had indexed colors?

So, I have an image cv::Mat created as an indexed 2D matrix with colors 1,2,3,... up to 255. I want to resize my image all at once but do it like I currently do - individually for each index, so as not to get mixed colors:
//...
std::map<unsigned char , cv::Mat* > clusters;
for(int i = 0; i < sy; ++i)
{
for(int j = 0; j < sx; ++j)
{
unsigned char current_k = image[i][j];
if (clusters[current_k] == NULL) {
clusters[current_k] = new cv::Mat();
(*clusters[current_k]) = cv::Mat::zeros(cv::Size(sx, sy), CV_8UC1);
}
(*clusters[current_k]).row(i).col(j) = 255;
}
}
std::vector<cv::Mat> result;
for( std::map<unsigned char, cv::Mat*>::iterator it = clusters.begin(); it != clusters.end(); ++it )
{
cv::Mat filled(cv::Size(w, h), (*it->second).type());
cv::resize((*it->second), filled, filled.size(), 0,0, CV_INTER_CUBIC);
cv::threshold( filled, filled, 1, 255, CV_THRESH_BINARY);
result.push_back(filled);
}
So, can OpenCV help me with the automation of my indexed image (so that I could not create cv::Mat per each cluster for a correct resize)?
you can use the Remap function with your own mash to interpolate the values as you'de like
take a look at this tutorial (Link)

opencv background substraction

I have an image of the background scene and an image of the same scene with objects in front. Now I want to create a mask of the object in the foreground with background substraction. Both images are RGB.
I have already created the following code:
cv::Mat diff;
diff.create(orgImage.dims, orgImage.size, CV_8UC3);
diff = abs(orgImage-refImage);
cv::Mat mask(diff.rows, diff.cols, CV_8U, cv::Scalar(0,0,0));
//mask = (diff > 10);
for (int j=0; j<diff.rows; j++) {
// get the address of row j
//uchar* dataIn= diff.ptr<uchar>(j);
//uchar* dataOut= mask.ptr<uchar>(j);
for (int i=0; i<diff.cols; i++) {
if(diff.at<cv::Vec3b>(j,i)[0] > 30 || diff.at<cv::Vec3b>(j,i)[1] > 30 || diff.at<cv::Vec3b>(j,i)[2] > 30)
mask.at<uchar>(j,i) = 255;
}
}
I dont know if I am doing this right?
Have a look at the inRange function from OpenCV. This will allow you to set multiple thresholds at the same time for a 3 channel image.
So, to create the mask you were looking for, do the following:
inRange(diff, Scalar(30, 30, 30), Scalar(255, 255, 255), mask);
This should also be faster than trying to access each pixel yourself.
EDIT : If skin detection is what you are trying to do, I would first do skin detection, and then afterwards do background subtraction to remove the background. Otherwise, your skin detector will have to take into account the intensity shift caused by the subtraction.
Check out my other answer, about good techniques for skin detection.
EDIT :
Is this any faster?
int main(int argc, char* argv[])
{
Mat fg = imread("fg.jpg");
Mat bg = imread("bg.jpg");
cvtColor(fg, fg, CV_RGB2YCrCb);
cvtColor(bg, bg, CV_RGB2YCrCb);
Mat distance = Mat::zeros(fg.size(), CV_32F);
vector<Mat> fgChannels;
split(fg, fgChannels);
vector<Mat> bgChannels;
split(bg, bgChannels);
for(size_t i = 0; i < fgChannels.size(); i++)
{
Mat temp = abs(fgChannels[i] - bgChannels[i]);
temp.convertTo(temp, CV_32F);
distance = distance + temp;
}
Mat mask;
threshold(distance, mask, 35, 255, THRESH_BINARY);
Mat kernel5x5 = getStructuringElement(MORPH_RECT, Size(5, 5));
morphologyEx(mask, mask, MORPH_OPEN, kernel5x5);
imshow("fg", fg);
imshow("bg", bg);
imshow("mask", mask);
waitKey();
return 0;
}
This code produces this mask based on your input imagery:
Finally, here is what I get using my simple thresholding method:
Mat diff = fgYcc - bgYcc;
vector<Mat> diffChannels;
split(diff, diffChannels);
// only operating on luminance for background subtraction...
threshold(diffChannels[0], bgfgMask, 1, 255.0, THRESH_BINARY_INV);
Mat kernel5x5 = getStructuringElement(MORPH_RECT, Size(5, 5));
morphologyEx(bgfgMask, bgfgMask, MORPH_OPEN, kernel5x5);
This produce the following mask:
I think when I'm doing it like this I get the right results: (in the YCrCb colorspace) but accessing each px is slow so I need to find another algorithm
cv::Mat mask(image.rows, image.cols, CV_8U, cv::Scalar(0,0,0));
cv::Mat_<cv::Vec3b>::const_iterator itImage= image.begin<cv::Vec3b>();
cv::Mat_<cv::Vec3b>::const_iterator itend= image.end<cv::Vec3b>();
cv::Mat_<cv::Vec3b>::iterator itRef= refRoi.begin<cv::Vec3b>();
cv::Mat_<uchar>::iterator itMask= mask.begin<uchar>();
for ( ; itImage!= itend; ++itImage, ++itRef, ++itMask) {
int distance = abs((*itImage)[0]-(*itRef)[0])+
abs((*itImage)[1]-(*itRef)[1])+
abs((*itImage)[2]-(*itRef)[2]);
if(distance < 30)
*itMask = 0;
else
*itMask = 255;
}

Resources