OpenCVで色検出

下記を参考にしてキャプチャした画像のRGBの割合を出してみた。

http://opencv.jp/sample/simple_gui.html
http://imagingsolution.blog107.fc2.com/blog-entry-99.html
http://gihyo.jp/dev/feature/01/opencv?ard=1461515703

#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <ctype.h>
#include <unistd.h>
#include <stdio.h>

int
main (int argc, char **argv)
{
  CvCapture *capture = 0;
  IplImage *frame = 0;
  double w = 320, h = 240;
  int c;
  int blue_pixels = 0;
  int green_pixels = 0;
  int red_pixels = 0;

  // (1)コマンド引数によって指定された番号のカメラに対するキャプチャ構造体を作成する
  if (argc == 1 || (argc == 2 && strlen (argv[1]) == 1 && isdigit (argv[1][0])))
    capture = cvCreateCameraCapture (argc == 2 ? argv[1][0] - '0' : 0);

  /* この設定は,利用するカメラに依存する */
  // (2)キャプチャサイズを設定する.
  cvSetCaptureProperty (capture, CV_CAP_PROP_FRAME_WIDTH, w);
  cvSetCaptureProperty (capture, CV_CAP_PROP_FRAME_HEIGHT, h);

  cvNamedWindow ("Capture", CV_WINDOW_AUTOSIZE);

  // (3)カメラから画像をキャプチャする
  while (1) {
    frame = cvQueryFrame (capture);
    for(int y = 0; y < frame->height; y++){
        for(int x = 0; x < frame->width; x++){
            /* imageDataはchar型なので 0-127? */
            blue_pixels += frame->imageData[frame->widthStep * y + x * 3] > 70;
            green_pixels+= frame->imageData[frame->widthStep * y + x * 3 + 1] > 70;
            red_pixels += frame->imageData[frame->widthStep * y + x * 3 + 2] > 70;
         }
    }

    printf("red_pixels=%d,%d\n",red_pixels,(red_pixels * 100)/(frame->width * frame->height));
    printf("green_pixels=%d,%d\n",green_pixels,(green_pixels * 100)/(frame->width * frame->height));
    printf("blue_pixels=%d,%d\n",blue_pixels,(blue_pixels * 100)/(frame->width * frame->height));
    fflush( stdout ); 
    cvShowImage ("Capture", frame);
    red_pixels = 0;a
    green_pixels = 0;
    blue_pixels = 0;
    c = cvWaitKey (2);
    if (c == '\x1b')
      break;

    sleep(1);
  }

  cvReleaseCapture (&capture);
  cvDestroyWindow ("Capture");

  return 0;
}