Soroush Rabiei
Soroush Rabiei

Reputation: 10868

How to convert 3-channel IplImage to 8-bit?

I need to convert a 3-channel image to 1-channel in order to use Hough circle transform. The image is a GBR captured from camera of my laptop:

// Laptop integrated camera (Dell inspiron 5010):
CvCapture* camera = cvCreateCameraCapture(0);
// ...
IplImage* image=cvQueryFrame(camera);
// Error:
CvSeq* results = cvHoughCircles( image, storage, CV_HOUGH_GRADIENT, 2, image->width/10);
// ...

Upvotes: 2

Views: 6862

Answers (2)

mevatron
mevatron

Reputation: 14021

You may want to just use cvCvtColor.

IplImage* dst = cvCreateImage(cvGetSize(src), IPL_DEPTH_8U, 1);
cvCvtColor(src, dst, CV_RGB2GRAY);

This will convert a 3-channel image to a single channel grayscale image. Also, if you're early on in your project I would recommend using the C++ API as it is much less "clunky" than the C API.

You could do the same type of program with the following code:

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

using namespace std;
using namespace cv;

int main(int argc, char** argv)
{
    Mat frame, gray;
    VideoCapture video(0);

    if(video.isOpened())
    {
        int key = 0;
        do
        {
            video >> frame;
            if(frame.empty())
            {
                break;
            }

            cvtColor(frame, gray, CV_BGR2GRAY);

            // smooth it, otherwise a lot of false circles may be detected
            GaussianBlur( gray, gray, Size(9, 9), 2, 2 );
            vector<Vec3f> circles;
            HoughCircles(gray, circles, CV_HOUGH_GRADIENT,
                         2, gray.rows / 4, 200, 100 );
            for( size_t i = 0; i < circles.size(); i++ )
            {
                 Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
                 int radius = cvRound(circles[i][2]);
                 // draw the circle center
                 circle( frame, center, 3, Scalar(0,255,0), -1, 8, 0 );
                 // draw the circle outline
                 circle( frame, center, radius, Scalar(0,0,255), 3, 8, 0 );
            }

            namedWindow( "circles", 1 );
            imshow( "circles", frame );
            key = waitKey(33); // 30Hz video assumed...
        } while((char)key != 27); // press ESC to exit
    }

    return 0;
}

Much cleaner without all of the pointer managment :)

Upvotes: 4

Andrey Rubshtein
Andrey Rubshtein

Reputation: 20915

Use cvSplit:

void splitMyImage( IplImage* src){
    // Allocate image planes
    IplImage* r = cvCreateImage( cvGetSize(src), IPL_DEPTH_8U, 1 );
    IplImage* g = cvCreateImage( cvGetSize(src), IPL_DEPTH_8U, 1 );
    IplImage* b = cvCreateImage( cvGetSize(src), IPL_DEPTH_8U, 1 );
    // Split image onto the color planes
    cvSplit( src, r, g, b, NULL );
}

Taken from:

http://dasl.mem.drexel.edu/~noahKuntz/openCVTut4.html

Upvotes: 0

Related Questions