Exemple #1
0
void gli_draw_pixel_lcd(int x, int y, unsigned char *alpha, unsigned char *rgb)
{
    unsigned char *p = gli_image_rgb + y * gli_image_s + x * gli_bpp;
    unsigned char invalf[3];
        invalf[0] = 255 - alpha[0];
        invalf[1] = 255 - alpha[1];
        invalf[2] = 255 - alpha[2];
    if (x < 0 || x >= gli_image_w)
        return;
    if (y < 0 || y >= gli_image_h)
        return;
#ifdef WIN32
    p[0] = rgb[2] + mul255((short)p[0] - rgb[2], invalf[2]);
    p[1] = rgb[1] + mul255((short)p[1] - rgb[1], invalf[1]);
    p[2] = rgb[0] + mul255((short)p[2] - rgb[0], invalf[0]);
#elif defined __APPLE__ || defined EFL_4BPP
    p[0] = rgb[2] + mul255((short)p[0] - rgb[2], invalf[2]);
    p[1] = rgb[1] + mul255((short)p[1] - rgb[1], invalf[1]);
    p[2] = rgb[0] + mul255((short)p[2] - rgb[0], invalf[0]);
    p[3] = 0xFF;
#elif defined EFL_1BPP
    int gray = grayscale( rgb[0], rgb[1], rgb[2] );
    int invalfgray = grayscale( invalf[0], invalf[1], invalf[2] );
    p[0] = gray + mul255((short)p[0] - gray, invalfgray);
#else
    p[0] = rgb[0] + mul255((short)p[0] - rgb[0], invalf[0]);
    p[1] = rgb[1] + mul255((short)p[1] - rgb[1], invalf[1]);
    p[2] = rgb[2] + mul255((short)p[2] - rgb[2], invalf[2]);
#endif
}
    virtual void onDraw(SkCanvas* canvas) {

        SkRect r = SkRect::MakeWH(FILTER_WIDTH, FILTER_HEIGHT);
        SkPaint paint;
        paint.setColor(SK_ColorRED);
        canvas->save();
        for (float brightness = -1.0f; brightness <= 1.0f; brightness += 0.2f) {
            SkAutoTUnref<SkImageFilter> dim(make_brightness(-brightness));
            SkAutoTUnref<SkImageFilter> bright(make_brightness(brightness, dim));
            paint.setImageFilter(bright);
            drawClippedRect(canvas, r, paint);
            canvas->translate(FILTER_WIDTH + MARGIN, 0);
        }
        canvas->restore();
        canvas->translate(0, FILTER_HEIGHT + MARGIN);
        {
            SkAutoTUnref<SkImageFilter> brightness(make_brightness(0.9f));
            SkAutoTUnref<SkImageFilter> grayscale(make_grayscale(brightness));
            paint.setImageFilter(grayscale);
            drawClippedRect(canvas, r, paint);
            canvas->translate(FILTER_WIDTH + MARGIN, 0);
        }
        {
            SkAutoTUnref<SkImageFilter> grayscale(make_grayscale());
            SkAutoTUnref<SkImageFilter> brightness(make_brightness(0.9f, grayscale));
            paint.setImageFilter(brightness);
            drawClippedRect(canvas, r, paint);
            canvas->translate(FILTER_WIDTH + MARGIN, 0);
        }
        {
            SkAutoTUnref<SkImageFilter> blue(make_mode_blue());
            SkAutoTUnref<SkImageFilter> brightness(make_brightness(1.0f, blue));
            paint.setImageFilter(brightness);
            drawClippedRect(canvas, r, paint);
            canvas->translate(FILTER_WIDTH + MARGIN, 0);
        }
        {
            SkAutoTUnref<SkImageFilter> brightness(make_brightness(1.0f));
            SkAutoTUnref<SkImageFilter> blue(make_mode_blue(brightness));
            paint.setImageFilter(blue);
            drawClippedRect(canvas, r, paint);
            canvas->translate(FILTER_WIDTH + MARGIN, 0);
        }
        {
            SkAutoTUnref<SkImageFilter> blur(make_blur(3.0f));
            SkAutoTUnref<SkImageFilter> brightness(make_brightness(0.5f, blur));
            paint.setImageFilter(brightness);
            drawClippedRect(canvas, r, paint, 3);
            canvas->translate(FILTER_WIDTH + MARGIN, 0);
        }
        {
            SkAutoTUnref<SkImageFilter> blue(make_mode_blue());
            paint.setImageFilter(blue.get());
            drawClippedRect(canvas, r, paint, 5);
            canvas->translate(FILTER_WIDTH + MARGIN, 0);
        }
    }
void FluxTensorMethod :: convert2grayscale(const Mat & input, Mat & output)
{
	Mat grayscale(input.size(), CV_8U);
	output = grayscale.clone();

    double rgb[3];
    const uchar * input_pixel_ptr;
    uchar * result_pixel_ptr;
    uchar gray_value;

    int height = input.rows;
    int width = input.cols;
    for(int row = 0; row < height; ++row)
    {
    	input_pixel_ptr = input.ptr(row);
        result_pixel_ptr = output.ptr(row);
        for(int col = 0; col < width; ++col)
        {
            //RGB reverted order
            rgb[2] = (double) *input_pixel_ptr++;
            rgb[1] = (double) *input_pixel_ptr++;
            rgb[0] = (double) *input_pixel_ptr++;
            //gray_value = (rgb[0]+rgb[1]+rgb[2])/3;
            gray_value = 0.2126*rgb[0]+0.7152*rgb[1]+0.0722*rgb[2];

            //for(int i = 0; i < 3; ++i)
                *result_pixel_ptr++ = gray_value;
        }
    }
}
Exemple #4
0
void gli_draw_clear(unsigned char *rgb)
{
    unsigned char *p;
    int x, y;
    
#ifdef EFL_1BPP
    int gray = grayscale( rgb[0], rgb[1], rgb[2] );
#endif
    for (y = 0; y < gli_image_h; y++)
    {
        p = gli_image_rgb + y * gli_image_s;
        for (x = 0; x < gli_image_w; x++)
        {
#ifdef WIN32
            *p++ = rgb[2];
            *p++ = rgb[1];
            *p++ = rgb[0];
#elif defined __APPLE__ || defined EFL_4BPP
            *p++ = rgb[2];
            *p++ = rgb[1];
            *p++ = rgb[0];
            *p++ = 0xFF;
#elif defined EFL_1BPP
            *p++ = gray;
#else
            *p++ = rgb[0];
            *p++ = rgb[1];
            *p++ = rgb[2];
#endif
        }
    }
}
 void onDraw(const int loops, SkCanvas* canvas) override {
     SkRect r = getFilterRect();
     SkPaint paint;
     paint.setColor(SK_ColorRED);
     for (int i = 0; i < loops; i++) {
         SkAutoTUnref<SkImageFilter> grayscale(make_grayscale());
         paint.setImageFilter(grayscale);
         canvas->drawRect(r, paint);
     }
 }
void GUI::apply_grayscale(Controller &controller) {

  if ( ! controller.image_file_loaded   ) { return ; }

  // Transform image into a grayscale image according choosen settings:

  switch (combo_current_grayscaling) {

    case 0 :

      grayscale(controller.current_image_to_process, controller.current_image_to_process, "average") ;
      break ;

    case 1 :

      grayscale(controller.current_image_to_process, controller.current_image_to_process, "max")     ;
      break ;

    case 2 :

      grayscale(controller.current_image_to_process, controller.current_image_to_process, "min")     ;
      break ;

    case 3 :

      grayscale(controller.current_image_to_process, controller.current_image_to_process, "red")     ;
      break ;

    case 4 :

      grayscale(controller.current_image_to_process, controller.current_image_to_process, "green")    ;
      break ;

    case 5 :

      grayscale(controller.current_image_to_process, controller.current_image_to_process, "blue")     ;
      break ;


    #ifdef DEBUG
    default :
      // Cannot append due of the GUI interfacing.
      fprintf(stdout,"Error applying grayscale filter !!!\n") ;
      return ;
   #endif

  }

  // We register current frame in vector<cv::Mat> for undo-redo.
  controller.process_after_applying() ;

  // It convert current_image_to_process as src to RGB(A) in dst current_image_to_display.
  set_img(controller.current_image_to_process, controller.current_image_to_display, controller) ;  // It auto process conversion to RGB(A).

  // Reset some variables.
  after_applying_reset_settings(controller) ;

}
Exemple #7
0
void gli_draw_rect(int x0, int y0, int w, int h, unsigned char *rgb)
{
    unsigned char *p0;
    int x1 = x0 + w;
    int y1 = y0 + h;
    int x, y;

    if (x0 < 0) x0 = 0;
    if (y0 < 0) y0 = 0;
    if (x1 < 0) x1 = 0;
    if (y1 < 0) y1 = 0;

    if (x0 > gli_image_w) x0 = gli_image_w;
    if (y0 > gli_image_h) y0 = gli_image_h;
    if (x1 > gli_image_w) x1 = gli_image_w;
    if (y1 > gli_image_h) y1 = gli_image_h;

    p0 = gli_image_rgb + y0 * gli_image_s + x0 * gli_bpp;

#ifdef EFL_1BPP
    int gray = grayscale( rgb[0], rgb[1], rgb[2] );
#endif
    for (y = y0; y < y1; y++)
    {
        unsigned char *p = p0;
        for (x = x0; x < x1; x++)
        {
#ifdef WIN32
            *p++ = rgb[2];
            *p++ = rgb[1];
            *p++ = rgb[0];
#elif defined __APPLE__ || defined EFL_4BPP
            *p++ = rgb[2];
            *p++ = rgb[1];
            *p++ = rgb[0];
            *p++ = 0xFF;
#elif defined EFL_1BPP
            *p++ = gray;
#else
            *p++ = rgb[0];
            *p++ = rgb[1];
            *p++ = rgb[2];
#endif
        }
        p0 += gli_image_s;
    }
}
Exemple #8
0
void P6::Monochrome(const char* filename)
{
	if (isGrayMonochrome() == true)
	{
		cout << "The image is already monochrome \n";
		return;
	}
	else
	{
		char* newName = ChangeFileName(filename, "_monochrome.ppm");
		ofstream outFile(newName, ios::out);
		if (!outFile)
		{
			cerr << "Cannot write P6 file \n";
			return;
		}
		char magic_pbm[3] = "P6";
		outFile << magic_pbm << endl << getWidth() << " " << getHeight() << endl << getMaxNum() << endl;

		int r = 0, g = 0, b = 0;
		for (int i = 0; i < getHeight(); i++)
		{
			for (int j = 0; j < getWidth(); j++)
			{
				r = getPixels()[i][j].getRed();
				g = getPixels()[i][j].getGreen();
				b = getPixels()[i][j].getBlue();

				int gray = grayscale(r, g, b);
				int m = monochrome(gray);

				outFile.write((const char*)&m, sizeof(char));
				outFile.write((const char*)&m, sizeof(char));
				outFile.write((const char*)&m, sizeof(char));
			}
		}

		outFile.flush();
		outFile.close();
		delete[] newName;
	}
}
void ImggFormatsConvertViewQtWidget::writeImg(
    MatrixWorkspace_sptr inWks, const std::string &outputName,
    const std::string &outFormat) const {
  if (!inWks)
    return;
  auto width = inWks->getNumberHistograms();
  if (0 == width)
    return;
  auto height = inWks->blocksize();

  QImage img(QSize(static_cast<int>(width), static_cast<int>(height)),
             QImage::Format_Indexed8);

  int tableSize = 256;
  QVector<QRgb> grayscale(tableSize);
  for (int i = 0; i < grayscale.size(); i++) {
    int level = i; // would be equivalent: qGray(i, i, i);
    grayscale[i] = qRgb(level, level, level);
  }
  img.setColorTable(grayscale);

  // only 16 to 8 bits color map supported with current libraries
  const double scaleFactor = std::numeric_limits<unsigned short int>::max() /
                             std::numeric_limits<unsigned char>::max();
  for (int yi = 0; yi < static_cast<int>(width); ++yi) {
    const auto &row = inWks->readY(yi);
    for (int xi = 0; xi < static_cast<int>(width); ++xi) {
      int scaled = static_cast<int>(row[xi] / scaleFactor);
      // Images not from IMAT, just crop. This needs much improvement when
      // we have proper Load/SaveImage algorithms
      if (scaled > 255)
        scaled = 255;
      if (scaled < 0)
        scaled = 0;
      img.setPixel(xi, yi, scaled);
    }
  }

  writeImgFile(img, outputName, outFormat);
}
int main(int argc, char **argv)
{
    ros::init(argc, argv, "sca_image_d_viewer");
    ros::NodeHandle n;

    ros::Subscriber scan_image_sub = n.subscribe("/scan_image", 1, scan_image_callback);
    ros::Subscriber image_sub = n.subscribe("/image_raw", 1, image_callback);
    ros::Subscriber car_fusion_sub = n.subscribe("/obj_car/image_obj_ranged", 1, car_fusion_callback);
    ros::Subscriber pedestrian_fusion_sub = n.subscribe("/obj_person/image_obj_ranged", 1, ped_fusion_callback);

    cv::Mat grayscale(256,1,CV_8UC1);
    for(int i = 0; i < 256; i++) {
        grayscale.at<uchar>(i)=i;
    }
    cv::applyColorMap(grayscale, colormap, cv::COLORMAP_JET);
    cvNamedWindow(window_name, 2);

    ros::spin();

    cvDestroyWindow(window_name);
    return 0;
}
Exemple #11
0
Canvas *
grayscale_canvas(Canvas * base,
                 int num_threads) {
    const int w = base->w;
    const int h = base->h;
    Canvas * ret = new_canvas(w, h);
    
    omp_set_num_threads((num_threads < 2) ? 1 : num_threads);
    
    int x;
    int y;
    #pragma omp parallel private(x, y)
    #pragma omp for collapse(2) schedule(dynamic, IMG_CHUNK)
    for(x = 0; x < w; ++x) {
        for(y = 0; y < h; ++y) {
            const Color c = get_pixel(x, y, base);
            const Color gray = grayscale(c);
            set_pixel(x, y, gray, ret);
        }
    }
    return ret;
}
Exemple #12
0
void P6::Grayscale(const char* filename)
{
	if (isGrayMonochrome() == true)
	{
		cout << "The image is already grayscale \n";
		return;
	}
	else
	{
		char* newName = ChangeFileName(filename, "_grayscale.ppm");
		ofstream outFile(newName, ios::out | ios::binary);
		if (!outFile)
		{
			cerr << "Cannot write P6 file \n";
			return;
		}
		char magic_pgm[3] = "P6";
		outFile << magic_pgm << endl << width << " " << height << endl << max_num << endl;

		for (int i = 0; i < getHeight(); i++)
		{
			for (int j = 0; j < getWidth(); j++)
			{
				r = getPixels()[i][j].getRed();
				g = getPixels()[i][j].getGreen();
				b = getPixels()[i][j].getBlue();

				int gray = grayscale(r, g, b);
				outFile.write((const char*)&gray, sizeof(Color) / 3);
				outFile.write((const char*)&gray, sizeof(Color) / 3);
				outFile.write((const char*)&gray, sizeof(Color) / 3);
			}
		}
		outFile.flush();
		outFile.close();
		delete[] newName;
	}	
}
int main(int argc, char **argv)
{
	/* create resizable window */
	cvNamedWindow(window_name, CV_WINDOW_NORMAL);
	cvStartWindowThread();

	ros::init(argc, argv, "vscan_image_viewer");
	ros::NodeHandle n;
	ros::Subscriber sub_image = n.subscribe("image_raw", 1, image_cb);
	ros::Subscriber sub_points = n.subscribe("vscan_image", 1, points_cb);

	cv::Mat grayscale(256,1,CV_8UC1);
	for(int i=0;i<256;i++)
	{
		grayscale.at<uchar>(i)=i;
	}
	cv::applyColorMap(grayscale,colormap,cv::COLORMAP_JET);

	ros::spin();

	cvDestroyWindow(window_name);

	return 0;
}
Exemple #14
0
int main (int argc, char **argv) {
    unsigned char *buf;
    long bufSize = 0;
    unsigned char *original;
    long originalSize = 0;
    unsigned char *originalGray = NULL;
    long originalGraySize = 0;
    unsigned char *compressed = NULL;
    unsigned long compressedSize = 0;
    unsigned char *compressedGray;
    long compressedGraySize = 0;
    unsigned char *tmpImage;
    int width, height;
    unsigned char *metaBuf;
    unsigned int metaSize = 0;
    FILE *file;

    // Parse commandline options
    command_t cmd;
    command_init(&cmd, argv[0], VERSION);
    cmd.usage = "[options] input.jpg compressed-output.jpg";
    command_option(&cmd, "-t", "--target [arg]", "Set target quality [0.9999]", setTarget);
    command_option(&cmd, "-q", "--quality [arg]", "Set a quality preset: low, medium, high, veryhigh [medium]", setQuality);
    command_option(&cmd, "-n", "--min [arg]", "Minimum JPEG quality [40]", setMinimum);
    command_option(&cmd, "-x", "--max [arg]", "Maximum JPEG quality [95]", setMaximum);
    command_option(&cmd, "-l", "--loops [arg]", "Set the number of runs to attempt [6]", setAttempts);
    command_option(&cmd, "-a", "--accurate", "Favor accuracy over speed", setAccurate);
    command_option(&cmd, "-m", "--method [arg]", "Set comparison method to one of 'mpe', 'ssim', 'ms-ssim', 'smallfry' [ssim]", setMethod);
    command_option(&cmd, "-s", "--strip", "Strip metadata", setStrip);
    command_option(&cmd, "-d", "--defish [arg]", "Set defish strength [0.0]", setDefish);
    command_option(&cmd, "-z", "--zoom [arg]", "Set defish zoom [1.0]", setZoom);
    command_option(&cmd, "-r", "--ppm", "Parse input as PPM instead of JPEG", setPpm);
    command_option(&cmd, "-c", "--no-copy", "Disable copying files that will not be compressed", setCopyFiles);
    command_option(&cmd, "-p", "--no-progressive", "Disable progressive encoding", setNoProgressive);
    command_parse(&cmd, argc, argv);

    if (cmd.argc < 2) {
        command_help(&cmd);
        return 255;
    }

    if (method == UNKNOWN) {
        fprintf(stderr, "Invalid method!");
        command_help(&cmd);
        return 255;
    }

    // No target passed, use preset!
    if (!target) {
        setTargetFromPreset();
    }

    // Read original
    bufSize = readFile((char *) cmd.argv[0], (void **) &buf);

    if (!bufSize) { return 1; }

    if (!ppm) {
        // Decode the JPEG
        originalSize = decodeJpeg(buf, bufSize, &original, &width, &height, JCS_RGB);
    } else {
        // Decode the PPM
        originalSize = decodePpm(buf, bufSize, &original, &width, &height);
    }

    if (defishStrength) {
        fprintf(stderr, "Defishing...\n");
        tmpImage = malloc(width * height * 3);
        defish(original, tmpImage, width, height, 3, defishStrength, defishZoom);
        free(original);
        original = tmpImage;
    }

    // Convert RGB input into Y
    originalGraySize = grayscale(original, &originalGray, width, height);

    if (!ppm) {
        // Read metadata (EXIF / IPTC / XMP tags)
        if (getMetadata(buf, bufSize, &metaBuf, &metaSize, COMMENT)) {
            fprintf(stderr, "File already processed by jpeg-recompress!\n");
            if (copyFiles) {
                file = openOutput(cmd.argv[1]);
                fwrite(buf, bufSize, 1, file);
                fclose(file);

                free(buf);

                return 0;
            } else {
                free(buf);
                return 2;
            }
        }
    }

    if (strip) {
        // Pretend we have no metadata
        metaSize = 0;
    } else {
        fprintf(stderr, "Metadata size is %ukb\n", metaSize / 1024);
    }

    if (!originalSize || !originalGraySize) { return 1; }

    // Do a binary search to find the optimal encoding quality for the
    // given target SSIM value.
    int min = jpegMin, max = jpegMax;
    for (int attempt = attempts - 1; attempt >= 0; --attempt) {
        float metric;
        int quality = min + (max - min) / 2;
        int progressive = attempt ? 0 : !noProgressive;
        int optimize = accurate ? 1 : (attempt ? 0 : 1);

        // Recompress to a new quality level, without optimizations (for speed)
        compressedSize = encodeJpeg(&compressed, original, width, height, JCS_RGB, quality, progressive, optimize);

        // Load compressed luma for quality comparison
        compressedGraySize = decodeJpeg(compressed, compressedSize, &compressedGray, &width, &height, JCS_GRAYSCALE);

        if (!compressedGraySize) {
          fprintf(stderr, "Unable to decode file that was just encoded!\n");
          return 1;
        }

        if (!attempt) {
            fprintf(stderr, "Final optimized ");
        }

        // Measure quality difference
        switch (method) {
            case MS_SSIM:
                metric = iqa_ms_ssim(originalGray, compressedGray, width, height, width, 0);
                fprintf(stderr, "ms-ssim");
                break;
            case SMALLFRY:
                metric = smallfry_metric(originalGray, compressedGray, width, height);
                fprintf(stderr, "smallfry");
                break;
            case MPE:
                metric = meanPixelError(originalGray, compressedGray, width, height, 1);
                fprintf(stderr, "mpe");
                break;
            case SSIM: default:
                metric = iqa_ssim(originalGray, compressedGray, width, height, width, 0, 0);
                fprintf(stderr, "ssim");
                break;
        }

        if (attempt) {
            fprintf(stderr, " at q=%i (%i - %i): %f\n", quality, min, max, metric);
        } else {
            fprintf(stderr, " at q=%i: %f\n", quality, metric);
        }

        if (metric < target) {
            if (compressedSize >= bufSize) {
                fprintf(stderr, "Output file would be larger than input!\n");
                free(compressed);
                free(compressedGray);

                if (copyFiles) {
                    file = openOutput(cmd.argv[1]);
                    fwrite(buf, bufSize, 1, file);
                    fclose(file);

                    free(buf);

                    return 0;
                } else {
                    free(buf);
                    return 1;
                }
            }

            switch (method) {
                case SSIM: case MS_SSIM: case SMALLFRY:
                    // Too distorted, increase quality
                    min = quality + 1;
                    break;
                case MPE:
                    // Higher than required, decrease quality
                    max = quality - 1;
                    break;
            }
        } else {
            switch (method) {
                case SSIM: case MS_SSIM: case SMALLFRY:
                    // Higher than required, decrease quality
                    max = quality - 1;
                    break;
                case MPE:
                    // Too distorted, increase quality
                    min = quality + 1;
                    break;
            }
        }

        // If we aren't done yet, then free the image data
        if (attempt) {
            free(compressed);
            free(compressedGray);
        }
    }

    free(buf);

    // Calculate and show savings, if any
    int percent = (compressedSize + metaSize) * 100 / bufSize;
    unsigned long saved = (bufSize > compressedSize) ? bufSize - compressedSize - metaSize : 0;
    fprintf(stderr, "New size is %i%% of original (saved %lu kb)\n", percent, saved / 1024);

    if (compressedSize >= bufSize) {
        fprintf(stderr, "Output file is larger than input, aborting!\n");
        return 1;
    }

    // Open output file for writing
    file = openOutput(cmd.argv[1]);

    // Write output
    fwrite(compressed, 20, 1, file); /* 0xffd8 and JFIF marker */

    // Write comment so we know not to reprocess this file
    // in the future if it gets passed in again.
    // 0xfffe (COM marker), two-byte big-endian length, string
    fputc(0xff, file);
    fputc(0xfe, file);
    fputc(0x00, file);
    fputc(32, file);
    fwrite(COMMENT, 30, 1, file);

    // Write metadata markers
    if (!strip && !ppm) {
        fwrite(metaBuf, metaSize, 1, file);
    }

    // Write image data
    fwrite(compressed + 20, compressedSize - 20, 1, file);
    fclose(file);

    // Cleanup
    command_free(&cmd);

    if (!strip && !ppm) {
        free(metaBuf);
    }

    free(compressed);
    free(original);
    free(originalGray);

    return 0;
}
/***************************************************************************//**
 * Menu_PointProcesses_ModifiedContrastStretch
 * Author - Derek Stotz
 *
 * Uses the QtImageLib to convert the image to a grayscale image.
 *
 * Parameters -
            image - the image object to manipulate.
 *
 * Returns
 *          true if successful, false if not
 ******************************************************************************/
bool PointProcessor::Menu_PointProcesses_ConvertToGreyscale(Image& image)
{
    return grayscale(image);
}
Exemple #16
0
int main(int argc, const char * argv[]) {
    
    int width,height,numPixels,i,rgb_color=255;
    char c,choice;
    
    FILE * inFile;
    inFile = fopen("Android_robot.png","r");
    
    c=getc(inFile);
    while(c=='#')
    {
        do
        {
            c=getc(inFile);
        }while (c!='\n');
        c=getc(inFile);
    }
    ungetc(c, inFile);
    
    // gusoma width na height birimuri  iyo file
    if(fscanf(inFile,"P6 %d %d",&width,&height)!=2)
    {
        fprintf(stderr, "invalid image size. \n");
        exit(1);
    }
    // gusoma RGB color components
    if(fscanf(inFile, "%d\n",&rgb_color)!=1)
    {
        fprintf(stderr, "invalid RGB color component. \n");
        exit(1);
    }
    //gucheckinga RGB deth niba ingana na yayindi twa defininze hejuru
    if(rgb_color!=RGB_COLOR)
    {
        fprintf(stderr, "Invalid RBG value.\n");
        exit(1);
    }
    
    //gushaka number of pixels zirimo
    numPixels = width*height;
    
    //kw allocatinga space ingana na number of pixels
    image = malloc(numPixels * sizeof(pixel_t));
    
    // ku readinga data ziri muri pixel
    for(i=0;i<numPixels;i++)
    {
        fscanf(inFile, "%c%c%c",&image[i].r,&image[i].g,&image[i].b);
    }
    
    // new header
    printf("P6\n");
    printf("%d %d 255\n",width,height);
    
    printf(" choose 1.filp image 2.grascale 3.rotate image .\n");
    scanf("%c",&choice);
    switch (choice) {
        case '1':
            flipImage(image,width, height);
            break;
        case '2':
            grayscale(image, width, height);
            break;
        case '3':
            //rotate(image, width, height);
            break;
        default:
            printf("invalid command");
            break;
    }
    return 0;
}
int main(int argc, char** argv) {
   
    
    /**Abertura do arquivo da imagem*/
    printf("%s\n","Informe o nome do arquivo de imagem a ser aberto:");
    scanf("%s",Nome_arquivo);
    
    /**Função limpa tela*/
    reset();
    
    FILE *arquivo;
    
    /**Ler o arquivo*/
    arquivo = fopen(Nome_arquivo, "r");
    
    /**Faz o teste de erro na abertura do arquivo*/
    if(arquivo == NULL){
        printf("%s\n","Erro ao abrir o arquivo de imagem.");
    }else{
        printf("%s\n","Arquivo de imagem aberto com sucesso."); 
    }
    
        /**Ler os dados do cabeçalho*/
        fscanf(arquivo, "P3 %i %i 255",&largura, &altura);
    
    /**Comparação para ver o maior valor da matriz*/
    if (largura > altura) {
        
        max = largura;
    }else{
        max = altura;
    }
    
    /**Cria uma variável do tipo struct*/
    Pixel imagem[max][max];
    

    /**Ler cada Pixel alocando na variável referente ao struct*/
    for (i = 0; i < altura; i++){
        for(j = 0; j < largura; j++){
            fscanf(arquivo, "%i %i %i", &imagem[i][j].r, &imagem[i][j].g, &imagem[i][j].b);
        }
    }
    /**fecha o arquivo*/
    fclose(arquivo);
    




    do{
        
        /**Menu do programa sendo chamado*/
        menu();

        printf("\nDigite o comando:>");
        /**Comando para leitura do menu*/
        scanf("%s",comando);
        reset();
   
        /**converte as letras para minusculo afim de facilitar a comparação*/
        for(i=0;comando[i];i++)
            comando[i]=tolower(comando[i]);
   
        
       
        if(strcmp(comando,"lap")==0){
            printf("\nExecutando o comando: %s\n", comando);
            /**Chama o Filtro de laplace*/
            laplace(imagem);
            printf("%s\n", "Informe o nome desejado para saída:");
            /**Ler o novo nome para a imagem*/
            scanf("%s",arq);
            gerar_img(imagem, arq);
            printf("%s\n", "Imagem tratada com sucesso.");
            return (EXIT_SUCCESS);
            
        }else if(strcmp(comando,"gau")==0){
            printf("\nExecutando o comando: %s\n", comando);
            /**Chama o filtro de gaus*/
            gaussiano(imagem);
            printf("%s\n", "Informe o nome desejado para saída:");
            /**Ler o novo nome para a imagem*/
            scanf("%s",arq);
            gerar_img(imagem, arq);
            printf("%s\n", "Imagem tratada com sucesso.");
            return (EXIT_SUCCESS);
            
        }else if(strcmp(comando,"blu")==0){
            printf("\nExecutando o comando: %s\n", comando);
            /**Chama o filtro Blurring*/
            passa_baixa(imagem);
            printf("%s\n", "Informe o nome desejado para saída:");
            /**Ler o novo nome para a imagem*/
            scanf("%s",arq);
            gerar_img(imagem, arq);
            printf("%s\n", "Imagem tratada com sucesso.");
            return (EXIT_SUCCESS);
            
        }else if(strcmp(comando,"sha")==0){
            printf("\nExecutando o comando: %s\n", comando);
            /**Chama o filtro sharpening*/
            passa_alta(imagem);
            printf("%s\n", "Informe o nome desejado para saída:");
            /**Ler o novo nome para a imagem*/
            scanf("%s",arq);
            gerar_img(imagem, arq);
            printf("%s\n", "Imagem tratada com sucesso.");
            return (EXIT_SUCCESS);
            
        }else if(strcmp(comando,"amp")==0){
            printf("\nExecutando o comando: %s\n", comando);
           
            printf("\nInforme o zoom desejado:\n");
            /**Ler o zoom para ampliar a imagem*/
            scanf("%i",&zoom);
           
           
            printf("%s\n", "Informe o nome desejado para saída:");
            scanf("%s",arq);
            /**Chama a função para ampliar da imagem*/
            ampliar_img(strcat(arq,".ppm"),zoom,imagem);
            
            printf("%s\n", "Imagem ampliada com sucesso.");
            return (EXIT_SUCCESS);
            
        }else if(strcmp(comando,"red")==0){
            printf("\nExecutando o comando: %s\n", comando);
           
            printf("\nInforme o zoom desejado:\n");
            /**Ler o zoom para reduzir a imagem*/
            scanf("%i",&zoom);
           
           
            printf("%s\n", "Informe o nome desejado para saída:");
            scanf("%s",arq);
            /**Chama a função para redução da imagem*/
            reduzir_img(strcat(arq,".ppm"),zoom,imagem);
            
            printf("%s\n", "Imagem reduzida com sucesso.");
            return (EXIT_SUCCESS);
            
        }else if(strcmp(comando,"rel")==0){
            printf("\nExecutando o comando: %s\n", comando);
            /**Chama o filtro para aplicar o relevo na imagem*/
            relevo(imagem);
            printf("%s\n", "Informe o nome desejado para saída:");
            /**Ler o novo nome para a imagem*/
            scanf("%s",arq);
            gerar_img(imagem, arq);
            printf("%s\n", "Imagem tratada com sucesso.");
            return (EXIT_SUCCESS);
            
        }else if(strcmp(comando,"thr")==0){
            printf("\nExecutando o comando: %s\n", comando);
            printf("\nInforme o valor do thresholding:\n");
            scanf("%i",&thr);
            /**Chama o filtro da binarização*/
            binarization(imagem, thr);
            printf("%s\n", "Informe o nome desejado para saída:");
            /**Ler o novo nome para a imagem*/
            scanf("%s",arq);
            gerar_img(imagem, arq);
            printf("%s\n", "Imagem binarizada com sucesso.");
            return (EXIT_SUCCESS);

        }else if(strcmp(comando,"gra")==0){
            printf("\nExecutando o comando: %s\n", comando);
            /**Chama o filtro para grayscale*/
            grayscale(imagem);
            printf("%s\n", "Informe o nome desejado para saída:");
            /**Ler o novo nome para a imagem*/
            scanf("%s",arq);
            gerar_img(imagem, arq);
            printf("%s\n", "Imagem tratada com sucesso.");
            return (EXIT_SUCCESS);
            
        }else if(strcmp(comando,"inv")==0){
            printf("\nExecutando o comando: %s\n", comando);
            /**Chama o filtro para inverter as cores*/
            inverter(imagem);
            printf("%s\n", "Informe o nome desejado para saída:");
            /**Ler o novo nome para a imagem*/
            scanf("%s",arq);
            gerar_img(imagem, arq);
            printf("%s\n", "Imagem tratada com sucesso.");
            return (EXIT_SUCCESS);

        }else if(strcmp(comando,"esp")==0){
            printf("\nExecutando o comando: %s\n", comando);
            /**Chama a função para espelhar a imagem*/
            espelhar(imagem);
            printf("%s\n", "Informe o nome desejado para saída:");
            /**Ler o novo nome para a imagem*/
            scanf("%s",arq);
            gerar_img(imagem, arq);
            printf("%s\n", "Imagem espelhada com sucesso.");
            return (EXIT_SUCCESS);

        }else if(strcmp(comando,"rot")==0){
            printf("%s\n", "Informe o ângulo desejado desejado (90, 180, 270):");
            /**Detalha o ângulo de rotação*/
            scanf("%i",&angulo);
			
		if(angulo == 90){
			printf("\nExecutando o comando: %s\n", comando);
            /**Chama a função para rotacionar a imagem*/
            rotacionar_esq(imagem);
			printf("%s\n", "Informe o nome desejado para saída:");
            /**Ler o novo nome para a imagem*/
            scanf("%s",arq);
			gerar_img(imagem, arq);
            printf("%s\n", "Imagem rotacionada com sucesso.");
           	return (EXIT_SUCCESS);
            
		}else if(angulo == 180){
			printf("\nExecutando o comando: %s\n", comando);
            rotacionar_180(imagem);
			printf("%s\n", "Informe o nome desejado para saída:");
            /**Ler o novo nome para a imagem*/
            scanf("%s",arq);
			gerar_img(imagem, arq);
            printf("%s\n", "Imagem rotacionada com sucesso.");
           	return (EXIT_SUCCESS);
		
		}else if(angulo == 270){
			printf("\nExecutando o comando: %s\n", comando);
            rotacionar_270(imagem);
			printf("%s\n", "Informe o nome desejado para saída:");
            /**Ler o novo nome para a imagem*/
            scanf("%s",arq);
			gerar_img(imagem, arq);
            printf("%s\n", "Imagem rotacionada com sucesso.");
           	return (EXIT_SUCCESS);
		}
        }else{
            /** chama a funcao limpa tela*/
            reset();
            printf("\nComando desconhecido: %s\n",comando);
            
        }    

    }while(strcmp(comando,"exit")!=0);



        printf("%s\n", "Programa finalizado");
    
    /**Finaliza o programa*/
    return (EXIT_SUCCESS);
}
int main(int argc, char **argv)
{
  /* create resizable window */
  cvNamedWindow(window_name, CV_WINDOW_NORMAL);
  cvStartWindowThread();

  ros::init(argc, argv, "points_image_d_viewer");
  ros::NodeHandle n;
  ros::NodeHandle private_nh("~");

  std::string image_topic_name;
  std::string car_node;
  std::string pedestrian_node;
  std::string points_node;

  if (private_nh.getParam("image_raw_topic", image_topic_name)) {
    ROS_INFO("Setting image topic to %s", image_topic_name.c_str());
  } else {
    ROS_INFO("No image topic received, defaulting to image_raw, you can use _image_raw_topic:=YOUR_NODE");
    image_topic_name = "/image_raw";
  }

  if (private_nh.getParam("car_node", car_node)) {
    ROS_INFO("Setting car positions node to %s", car_node.c_str());
  } else {
    ROS_INFO("No car positions node received, defaulting to car_pixel_xyz, you can use _car_node:=YOUR_TOPIC");
    car_node = "/obj_car/image_obj_ranged";
  }

  if (private_nh.getParam("pedestrian_node", pedestrian_node)) {
    ROS_INFO("Setting pedestrian positions node to %s", pedestrian_node.c_str());
  } else {
    ROS_INFO("No pedestrian positions node received, defaulting to pedestrian_pixel_xyz, you can use _pedestrian_node:=YOUR_TOPIC");
    pedestrian_node = "/obj_person/image_obj_ranged";
  }

  if (private_nh.getParam("points_node", points_node)) {
    ROS_INFO("Setting pedestrian positions node to %s", points_node.c_str());
  } else {
    ROS_INFO("No points node received, defaulting to points_image, you can use _points_node:=YOUR_TOPIC");
    points_node = "/points_image";
  }

#if (CV_MAJOR_VERSION == 3)
	generateColors(_colors, 25);
#else
	cv::generateColors(_colors, 25);
#endif

  ros::Subscriber scriber = n.subscribe(image_topic_name, 1,
                                        image_cb);
  ros::Subscriber scriber_car = n.subscribe(car_node, 1,
                                            car_updater_callback);
  ros::Subscriber scriber_ped = n.subscribe(pedestrian_node, 1,
                                            ped_updater_callback);
  ros::Subscriber scriber_points = n.subscribe(points_node, 1,
                                               points_cb);

  cv::Mat grayscale(256,1,CV_8UC1);
  for(int i=0;i<256;i++) {
    grayscale.at<uchar>(i)=i;
  }
  cv::applyColorMap(grayscale,colormap,cv::COLORMAP_JET);

  ros::spin();

  cvDestroyWindow(window_name);

  return 0;
}
Exemple #19
0
int main(int argc, char *argv[])
{
  if (argc != 4)
  {
    cout << "Usage: " << argv[0] << " cpu|gpu out_func out_prefix" << endl;
    return 1;
  }

  ImageParam input(UInt(8), 3, "input");
  Func clamped("clamped"), grayscale("grayscale");
  Func g_x("g_x"), g_y("g_y"), g_mag("g_mag");
  Func sobel("sobel");
  Var c("c"), x("x"), y("y");

  // Algorithm
  clamped(x, y, c) = input(
    clamp(x, 0, input.width()-1),
    clamp(y, 0, input.height()-1),
    c) / 255.f;
  grayscale(x, y) =
    clamped(x, y, 0)*0.299f +
    clamped(x, y, 1)*0.587f +
    clamped(x, y, 2)*0.114f;

  Image<int16_t> kernel(3, 3);
  kernel(0, 0) = -1;
  kernel(0, 1) = -2;
  kernel(0, 2) = -1;
  kernel(1, 0) = 0;
  kernel(1, 1) = 0;
  kernel(1, 2) = 0;
  kernel(2, 0) = 1;
  kernel(2, 1) = 2;
  kernel(2, 2) = 1;

  RDom r(kernel);
  g_x(x, y) += kernel(r.x, r.y) * grayscale(x + r.x - 1, y + r.y - 1);
  g_y(x, y) += kernel(r.y, r.x) * grayscale(x + r.x - 1, y + r.y - 1);
  g_mag(x, y) = sqrt(g_x(x, y)*g_x(x, y) + g_y(x, y)*g_y(x, y));
  sobel(x, y, c) = select(c==3, 255, u8(clamp(g_mag(x, y), 0, 1)*255));

  // Channel order
  input.set_stride(0, 4);
  input.set_extent(2, 4);
  sobel.reorder_storage(c, x, y);
  sobel.output_buffer().set_stride(0, 4);
  sobel.output_buffer().set_extent(2, 4);

  // Schedules
  if (!strcmp(argv[1], "cpu"))
  {
    sobel.parallel(y).vectorize(c, 4);
  }
  else if (!strcmp(argv[1], "gpu"))
  {
    sobel.cuda_tile(x, y, 16, 4);
  }
  else
  {
    cout << "Invalid schedule type '" << argv[1] << "'" << endl;
    return 1;
  }

  compile(sobel, input, argv[2], argv[3]);

  return 0;
}
Exemple #20
0
void gli_draw_picture(picture_t *src, int x0, int y0, int dx0, int dy0, int dx1, int dy1)
{
    unsigned char *sp, *dp;
    int x1, y1, sx0, sy0, sx1, sy1;
    int x, y, w, h;

    sx0 = 0;
    sy0 = 0;
    sx1 = src->w;
    sy1 = src->h;

    x1 = x0 + src->w;
    y1 = y0 + src->h;

    if (x1 <= dx0 || x0 >= dx1) return;
    if (y1 <= dy0 || y0 >= dy1) return;
    if (x0 < dx0)
    {
      sx0 += dx0 - x0;
      x0 = dx0;
    }
    if (y0 < dy0)
    {
      sy0 += dy0 - y0;
      y0 = dy0;
    }
    if (x1 > dx1)
    {
      sx1 += dx1 - x1;
      x1 = dx1;
    }
    if (y1 > dy1)
    {
      sy1 += dy1 - y1;
      y1 = dy1;
    }

    sp = src->rgba + (sy0 * src->w + sx0) * 4;
    dp = gli_image_rgb + y0 * gli_image_s + x0 * gli_bpp;

    w = sx1 - sx0;
    h = sy1 - sy0;

    for (y = 0; y < h; y++)
    {
        for (x = 0; x < w; x++)
        {
            unsigned char sa = sp[x*4+3];
            unsigned char na = 255 - sa;
            unsigned char sr = mul255(sp[x*4+0], sa);
            unsigned char sg = mul255(sp[x*4+1], sa);
            unsigned char sb = mul255(sp[x*4+2], sa);
#ifdef EFL_1BPP
            unsigned char sgray = grayscale(sr, sg, sb);
#endif
#ifdef WIN32
            dp[x*3+0] = sb + mul255(dp[x*3+0], na);
            dp[x*3+1] = sg + mul255(dp[x*3+1], na);
            dp[x*3+2] = sr + mul255(dp[x*3+2], na);
#elif defined __APPLE__ || defined EFL_4BPP
            dp[x*4+0] = sb + mul255(dp[x*4+0], na);
            dp[x*4+1] = sg + mul255(dp[x*4+1], na);
            dp[x*4+2] = sr + mul255(dp[x*4+2], na);
            dp[x*4+3] = 0xFF;
#elif defined EFL_1BPP
            dp[x] = sgray + mul255(dp[x], na);
#else
            dp[x*3+0] = sr + mul255(dp[x*3+0], na);
            dp[x*3+1] = sg + mul255(dp[x*3+1], na);
            dp[x*3+2] = sb + mul255(dp[x*3+2], na);
#endif
        }
        sp += src->w * 4;
        dp += gli_image_s;
    }
}
void Tracker::run()
{
    camera = cv::VideoCapture(camera_index);  
    if (force_width)
        camera.set(CV_CAP_PROP_FRAME_WIDTH, force_width);
    if (force_height)
        camera.set(CV_CAP_PROP_FRAME_HEIGHT, force_height);
    if (force_fps)
        camera.set(CV_CAP_PROP_FPS, force_fps);
    
    aruco::MarkerDetector detector;
    detector.setDesiredSpeed(3);
    detector.setThresholdParams(11, 6);

    cv::Rect last_roi(65535, 65535, 0, 0);

    cv::Mat color, color_, grayscale, rvec, tvec;

    const double stateful_coeff = 0.81;
    
    if (!camera.isOpened())
    {
        fprintf(stderr, "aruco tracker: can't open camera\n");
        return;
    }

    while (!stop)
        if(camera.read(color_))
            break;

    auto freq = cv::getTickFrequency();
    auto last_time = cv::getTickCount();
    int fps = 0;
    int last_fps = 0;
    cv::Point2f last_centroid;
    while (!stop)
    {
        if (!camera.read(color_))
            continue;
        auto tm = cv::getTickCount();
        color_.copyTo(color);
        cv::cvtColor(color, grayscale, cv::COLOR_BGR2GRAY);

        const int scale = frame.cols > 480 ? 2 : 1;

        const float focal_length_w = 0.5 * grayscale.cols / tan(0.5 * fov * HT_PI / 180);
        const float focal_length_h = 0.5 * grayscale.rows / tan(0.5 * fov * grayscale.rows / grayscale.cols * HT_PI / 180.0);
        cv::Mat intrinsics = cv::Mat::eye(3, 3, CV_32FC1);
        intrinsics.at<float> (0, 0) = focal_length_w;
        intrinsics.at<float> (1, 1) = focal_length_h;
        intrinsics.at<float> (0, 2) = grayscale.cols/2;
        intrinsics.at<float> (1, 2) = grayscale.rows/2;

        cv::Mat dist_coeffs = cv::Mat::zeros(5, 1, CV_32FC1);
        
        for (int i = 0; i < 5; i++)
            dist_coeffs.at<float>(i) = 0;
        
        std::vector< aruco::Marker > markers;

        if (last_roi.width > 0 &&
                (detector.detect(grayscale(last_roi), markers, cv::Mat(), cv::Mat(), -1, false),
                 markers.size() == 1 && markers[0].size() == 4))
        {
            detector.setMinMaxSize(std::max(0.2, 0.08 * grayscale.cols / last_roi.width),
                                   std::min(1.0, 0.39 * grayscale.cols / last_roi.width));
            auto& m = markers.at(0);
            for (int i = 0; i < 4; i++)
            {
                auto& p = m.at(i);
                p.x += last_roi.x;
                p.y += last_roi.y;
            }
        }
        else
        {
            detector.setMinMaxSize(0.09, 0.4);
            detector.detect(grayscale, markers, cv::Mat(), cv::Mat(), -1, false);
        }

        if (markers.size() == 1 && markers[0].size() == 4) {
            const aruco::Marker& m = markers.at(0);
            for (int i = 0; i < 4; i++)
                cv::line(color, m[i], m[(i+1)%4], cv::Scalar(0, 0, 255), scale, 8);
        }

        auto time = cv::getTickCount();

        if ((long) (time / freq) != (long) (last_time / freq))
        {
            last_fps = fps;
            fps = 0;
            last_time = time;
        }

        fps++;

        char buf[128];

        frame = color.clone();

        ::sprintf(buf, "Hz: %d", last_fps);
        cv::putText(frame, buf, cv::Point(10, 32), cv::FONT_HERSHEY_PLAIN, scale, cv::Scalar(0, 255, 0), scale);
        ::sprintf(buf, "Jiffies: %ld", (long) (10000 * (time - tm) / freq));
        cv::putText(frame, buf, cv::Point(10, 54), cv::FONT_HERSHEY_PLAIN, scale, cv::Scalar(80, 255, 0), scale);
        
        if (markers.size() == 1 && markers[0].size() == 4) {
            const aruco::Marker& m = markers.at(0);
            const float size = 7;
            
            cv::Mat obj_points(4,3,CV_32FC1);
            obj_points.at<float>(1,0)=-size + headpos[0];
            obj_points.at<float>(1,1)=-size + headpos[1];
            obj_points.at<float>(1,2)=0 + headpos[2];
            obj_points.at<float>(2,0)=size + headpos[0];
            obj_points.at<float>(2,1)=-size + headpos[1];
            obj_points.at<float>(2,2)=0 + headpos[2];
            obj_points.at<float>(3,0)=size + headpos[0];
            obj_points.at<float>(3,1)=size + headpos[1];
            obj_points.at<float>(3,2)=0 + headpos[2];
            obj_points.at<float>(0,0)=-size + headpos[0];
            obj_points.at<float>(0,1)=size + headpos[1];
            obj_points.at<float>(0,2)=0 + headpos[2];

            last_roi = cv::Rect(65535, 65535, 0, 0);

            for (int i = 0; i < 4; i++)
            {
                auto foo = m.at(i);
                last_roi.x = std::min<int>(foo.x, last_roi.x);
                last_roi.y = std::min<int>(foo.y, last_roi.y);
                last_roi.width = std::max<int>(foo.x, last_roi.width);
                last_roi.height = std::max<int>(foo.y, last_roi.height);
            }
            {
                last_roi.width -= last_roi.x;
                last_roi.height -= last_roi.y;
                last_roi.x -= last_roi.width * stateful_coeff;
                last_roi.y -= last_roi.height * stateful_coeff;
                last_roi.width *= stateful_coeff * 3;
                last_roi.height *= stateful_coeff * 3;
                last_roi.x = std::max<int>(0, last_roi.x);
                last_roi.y = std::max<int>(0, last_roi.y);
                last_roi.width = std::min<int>(grayscale.cols - last_roi.x, last_roi.width);
                last_roi.height = std::min<int>(grayscale.rows - last_roi.y, last_roi.height);
            }
            
            cv::solvePnP(obj_points, m, intrinsics, dist_coeffs, rvec, tvec, false, cv::ITERATIVE);
            
            cv::Mat rotation_matrix = cv::Mat::zeros(3, 3, CV_64FC1);
            
            cv::Mat junk1(3, 3, CV_64FC1), junk2(3, 3, CV_64FC1);
        
            cv::Rodrigues(rvec, rotation_matrix);
        
            {
                const double beta = headpitch * HT_PI / 180;
                double pitch[] = {
                    1, 0, 0,
                    0, cos(beta), -sin(beta),
                    0, sin(beta), cos(beta)
                };
                cv::Mat rot(3, 3, CV_64F, pitch);
                cv::Mat tvec2 = rot * tvec;
                rotation_matrix = rot * rotation_matrix;

                cv::Vec3d euler = cv::RQDecomp3x3(rotation_matrix, junk1, junk2);

                QMutexLocker lck(&mtx);

                for (int i = 0; i < 3; i++)
                    pose[i] = tvec2.at<double>(i);

                pose[Yaw] = euler[1];
                pose[Pitch] = -euler[0];
                pose[Roll] = euler[2];
            }

            std::vector<cv::Point2f> repr2;
            std::vector<cv::Point3f> centroid;
            centroid.push_back(cv::Point3f(0, 0, 0));
            cv::projectPoints(centroid, rvec, tvec, intrinsics, dist_coeffs, repr2);

            {
                auto s = cv::Scalar(255, 0, 255);
                cv::circle(frame, repr2.at(0), 4, s, -1);
            }

            last_centroid = repr2[0];
        }
        else
        {
            last_roi = cv::Rect(65535, 65535, 0, 0);
        }

        if (frame.rows > 0)
            videoWidget->update_image(frame);
    }
}
Exemple #22
0
int main(int argc, char **argv)
{
	unsigned short grafboard;
	extern int disk_error_handler(int errval, int ax, int bp, int si);
   char *p;

	allocatebuffers();
	if (init_mem_err)
   {
      cprintf("\r\n\r\nSorry, not enough memory to run Toy Universes.\r\n");
      return -1;
   }

	harderr(disk_error_handler);

	/* Find out if we have a VGA or EGA at all. */

	grafboard = QueryGrafix();


	if ((grafboard & 0x200) != 0x200)
	{
		printf("This programs requires EGA capability.\n");
		exit(-1);
	}

	if (grafboard == 0xffff || InitGrafix(-EGA640x350) < 0)
	{
		printf("Metagraphics not installed. Execute the command:\n");
		printf("metashel /i\n");
		printf("and then try again.\n");
		exit(-1);
	}

	vgaflag = -1;

	while (argc > 1)
	{
		if (argv[1][0] == '-')
		{
			switch (argv[1][1])
			{
			case 'e':
				vgaflag = 0;
				break;
         case 'v':
	    vgaflag = 1;
	    break;
			}
		}
		argc--;
		argv++;
	}

	if (vgaflag == -1)
	{
		if ((grafboard & 0x300) == 0x300)
			vgaflag = 1;
		else
			vgaflag = 0;
	}



	Comm = QueryComm();
	if (Comm == MsDriver)
		InitMouse(MsDriver);
	else if (Comm == MsCOM1)
		InitMouse(MsCOM1);
	else if (Comm == MsCOM2)
		InitMouse(MsCOM2);
	else if (Comm & 3)
		InitMouse(COM1);
	/*
	 * Probably wrong. Need to check for MS mouse address in some special
	 * way.
	 */


	randomize();


   p = searchpath("system16.fnt");
   if (p)
      LoadFont(p);
	installmode();

	load_preset_palettes();

	usepalette();

	current_main_item = 0;

	usepalette();
   TWICE(initialize_buttons());

	ShowCursor();
   if (allocatefailflag)
      ErrorBox("Not enough memory for hi-res.");

   /* Lets see if there is enough for a later gif */
   if (!memok(20712L))		    /* Added up mallocs in comprs.c */
           ErrorBox("There may not be enough memory to save or view a Gif.");


   prog_init = 1;

   if (!setjmp(beatit))
   {

	   while (!exitflag)
	   {

		   rebuildflag = 0;

		   if (newcaflag && !donescreenflag)
		   {
			   loadlookuptable(increment, maxstate);
			   newcaflag = 0;
		   }

		   if (newcaoflag)
		   {
	    unsigned char *p1,*p2;
	    static int firsttime = true;

	    switch(caotype)
	    {
	    case CA_HODGE:
	       p1 = (char *)HODGE_colortable;
	       p2 = HODGE_ct;
	       break;
	    case CA_EAT:
	       p1 = (char *)EAT_colortable;
	       p2 = EAT_ct;
	       break;
	    case CA_TUBE:
	       p1 = (char *)TUBE_colortable;
	       p2 = TUBE_ct;
	       break;
	    case CA_NLUKY:
	       p1 = (char *)NLUKY_colortable;
	       p2 = NLUKY_ct;
	       break;
	    }
	    memcpy(vgacolortable,p1,16*3);
	    if (!hasVGA)
	       memcpy(egacolortable,p2,16);


			   if (!firsttime)
	    {
	       TWICE(initialize_numbers());
	    }
	    else
	       firsttime = false;
			   usepalette();


			   newcaoflag = 0;
	    current_main_item = -1;
		   }

		   if (blankflag)
		   {
			   blankbuffers();
			   blankflag = 0;
		   }
		   if (randomizeflag)
		   {
			   carandomize();
			   randomizeflag = 0;
		   }
		   while (!exitflag && !rebuildflag)
		   {

			   if (onestep || !stopped)
			   {
				   if (display_mode == HI)
					   hiresupdate();
				   else
					   loresupdate();
				   if (onestep)
					   onestep--;

			   }
			   if (spinflag && (!stopped || (iteration++ > spinspeed)))
			   {
				   if (spinflag == 1)
					   spinpalette();
				   else
					   revspinpalette();
               iteration = 0;
			   }
			   checkkeyboard();

			   if (newcaflag)
				   rebuildflag = 1;
		   }
	   }
   }
	StopMouse();
	StopEvent();
	grayflag = 0;
	grayscale();
	SetDisplay(TextPg0);
	return exitflag;

}
int main( int argc , const char **argv )
{
  	cv::Mat src, dst;

	src = cv::imread( "person.jpg" , CV_LOAD_IMAGE_COLOR );
	
	if( src.empty() )
	{
		std::cerr << "Could not open or find the image!" << std::endl;

		return -1;
	}

	cv::namedWindow( "Source Image" , CV_WINDOW_AUTOSIZE );
		
	cv::Mat grayscale;
	cv::cvtColor( src , grayscale , CV_BGR2GRAY );
	cv::equalizeHist( grayscale , grayscale );
	
	cv::CascadeClassifier faceCascade, leftEyeCascade, rightEyeCascade, noseCascade, mouthCascade;
	faceCascade.load( "frontalface.xml" );
	leftEyeCascade.load( "lefteye.xml" );
	rightEyeCascade.load( "righteye.xml" );
	noseCascade.load( "nose.xml" );
	mouthCascade.load( "mouse.xml" );

	std::vector< cv::Rect > faces;
	faceCascade.detectMultiScale( grayscale , faces , 1.2 , 2 , CV_HAAR_DO_CANNY_PRUNING , cv::Size( 50 , 50 ) );

	dst.create( src.size() , src.type() );
	src.copyTo( dst );

	for( std::vector< cv::Rect >::iterator i = faces.begin() ; i != faces.end() ; ++i )
	{
		cv::rectangle( dst , cv::Rect( int( ( *i ).x ) , int( ( *i ).y ) , int( ( *i ).width ) , int( ( *i ).height ) ) , CV_RGB( 0 , 255 , 0 ) , 3 );

		cv::Mat face = grayscale( *i );
		
		std::vector< cv::Rect > leftEyes;
		leftEyeCascade.detectMultiScale( grayscale , leftEyes , 1.2 , 2 , CV_HAAR_DO_CANNY_PRUNING , cv::Size( 30 , 30 ) );
		
		cv::Point center( leftEyes[ 1 ].x + leftEyes[ 1 ].width * 0.5 , leftEyes[ 1 ].y + leftEyes[ 1 ].height * 0.5 );
		int radius = cvRound( ( leftEyes[ 1 ].width + leftEyes[ 1 ].height ) * 0.25 );
		cv::circle( dst , center , radius , CV_RGB( 255 , 0 , 0 ) , 2 );

		std::vector< cv::Rect > rightEyes;
		rightEyeCascade.detectMultiScale( grayscale , rightEyes , 1.2 , 2 , CV_HAAR_DO_CANNY_PRUNING , cv::Size( 30 , 30 ) );
		center = cv::Point( rightEyes[ 1 ].x + rightEyes[ 1 ].width * 0.5 , rightEyes[ 1 ].y + rightEyes[ 1 ].height * 0.5 );
		radius = cvRound( ( rightEyes[ 1 ].width + rightEyes[ 1 ].height ) * 0.25 );
		cv::circle( dst , center , radius , CV_RGB( 0 , 0 , 255 ) , 2 );

		std::vector< cv::Rect > noses;
		noseCascade.detectMultiScale( grayscale , noses , 1.2 , 2 , CV_HAAR_DO_CANNY_PRUNING , cv::Size( 30 , 30 ) );

		if( !noses.empty() )
			cv::rectangle( dst , cv::Rect( int( noses[ 0 ].x ) , int( noses[ 0 ].y ) , int( noses[ 0 ].width ) , int( noses[ 0 ].height ) ) , CV_RGB( 0 , 255 , 255 ) , 2 );
		
		std::vector< cv::Rect > mouthes;
		mouthCascade.detectMultiScale( grayscale , mouthes , 1.2 , 2 , CV_HAAR_DO_CANNY_PRUNING , cv::Size( 30 , 30 ) );

		if( !mouthes.empty() )
			cv::rectangle( dst , cv::Rect( int( mouthes[ 0 ].x ) , int( mouthes[ 0 ].y ) , int( mouthes[ 0 ].width ) , int( mouthes[ 0 ].height ) ) , CV_RGB( 255 , 255 , 0 ) , 2 );
	}

	imshow( "Source Image" , src );
	imshow( "Grayscale Image" , grayscale );
	imshow( "Face Detector" , dst );

	cv::waitKey( 0 );
	cv::destroyAllWindows();
	return 0;
}
void FaceDetector::imageCallback(const sensor_msgs::Image::ConstPtr& image_ptr)
{
#ifdef marco_debug
	ROS_INFO("imagecallback called");
#endif
	cv_bridge::CvImagePtr cv_ptr;
    try
    {
    	cv_ptr = cv_bridge::toCvCopy(image_ptr, sensor_msgs::image_encodings::RGB8);
    }
    catch (cv_bridge::Exception& e)
    {
	    ROS_ERROR("cv_bridge exception: %s", e.what());
	    return;
    }

    cv::Mat image_received = (cv_ptr->image).clone();
    image_size_ = cv_ptr->image.size();

    vector<cv::Rect> faces_roi;
    cv::Mat grayscale;
    cv::cvtColor(image_received,grayscale,CV_RGB2GRAY); // marco: converting to grayscale before haar detection
    detectFacesHaar(image_received, faces_roi,face_classifier_);

    if(faces_roi.size() > 0) //If Haar cascade classifier found a face
    {
#ifdef marco_debug
    		ROS_INFO("haar cascade found a face");
#endif
        vector<cv::Rect> eyes_roi;
        detectFacesHaar(grayscale(faces_roi[0]), eyes_roi,alternative_face_classifier_);
    	if (eyes_roi.size()>0)
    	{
        	//ROS_INFO("HAAR CLASSIFIER FOUND A FACE");
        	face_detected_bool_ = true;
        	track_object_ = false;

        		//Changed
        	detected_face_roi_ = faces_roi[0];
        	detected_face_ = cv_ptr->image(detected_face_roi_);

    	}
    	else face_detected_bool_=false;


    }
    else
    {
    	face_detected_bool_=false;
    }

    // >>>>>>>> KALMAN
    double precTick = ticks_;
    ticks_ = (double) cv::getTickCount();
    double dT = (ticks_ - precTick) / cv::getTickFrequency(); //seconds

    if (found_)
          {
             // >>>> Matrix A
             kalman_filter_.transitionMatrix.at<float>(2) = dT;
             kalman_filter_.transitionMatrix.at<float>(9) = dT;
             // <<<< Matrix A

             state_ = kalman_filter_.predict();
             //cout << "State post:" << endl << state_ << endl;
             cv::Rect predRect;
             predRect.width = state_.at<float>(4);
             predRect.height = state_.at<float>(5);
             predRect.x = state_.at<float>(0) - predRect.width / 2;
             predRect.y = state_.at<float>(1) - predRect.height / 2;
             cv::Point center;
             center.x = state_.at<float>(0);
             center.y = state_.at<float>(1);
             cv::circle(image_received, center, 2, CV_RGB(255,0,0), -1);
             cv::rectangle(image_received, predRect, CV_RGB(255,0,0), 2);
          }


    if (!face_detected_bool_)
    {
    	notFoundCount_++;
        //cout << "notFoundCount:" << notFoundCount_ << endl;
        if( notFoundCount_ >= 10 )
        {

            found_ = false;
        }
        else
        {
            kalman_filter_.statePost = state_;
        }
    }
    else
    {
    	notFoundCount_ = 0;

        meas_.at<float>(0) = (float)(detected_face_roi_.x + detected_face_roi_.width/2);
        meas_.at<float>(1) = (float)(detected_face_roi_.y + detected_face_roi_.height/2);
        meas_.at<float>(2) = (float)detected_face_roi_.width;
        meas_.at<float>(3) = (float)detected_face_roi_.height;

             if (!found_) // First detection!
             {
                // >>>> Initialization
                kalman_filter_.errorCovPre.at<float>(0) = 1; // px
                kalman_filter_.errorCovPre.at<float>(7) = 1; // px
                kalman_filter_.errorCovPre.at<float>(14) = 1;
                kalman_filter_.errorCovPre.at<float>(21) = 1;
                kalman_filter_.errorCovPre.at<float>(28) = 1; // px
                kalman_filter_.errorCovPre.at<float>(35) = 1; // px

                state_.at<float>(0) = meas_.at<float>(0);
                state_.at<float>(1) = meas_.at<float>(1);
                state_.at<float>(2) = 0;
                state_.at<float>(3) = 0;
                state_.at<float>(4) = meas_.at<float>(2);
                state_.at<float>(5) = meas_.at<float>(3);
                // <<<< Initialization

                found_ = true;
             }
             else
                kalman_filter_.correct(meas_); // Kalman Correction


           //  cout << "Measure matrix:" << endl << meas_ << endl;
          }


    float head_distance;
   // ROS_INFO("Computing head distance");
	if(!face_detected_bool_)
    {
	  if(head_distances_.size()!=0)
	  {
			head_distance=head_distances_[0];//100;
	  }
		else
		  head_distance = 3.0;


	}
	else
	{
		head_distance=calcDistanceToHead(detected_face_, kalman_filter_);
#ifdef marco_debug
		ROS_ERROR ("COMPUTED HEAD DISTANCE: %f",head_distance);
#endif

	}

    if(head_distances_.size()==0)
    {
      for(int i=0;i<10;i++)
	    head_distances_.push_back(head_distance);
    }
    else
    {
      head_distances_.pop_back();
      head_distances_.insert(head_distances_.begin(),head_distance);
    }
#ifdef marco_debug
    ROS_INFO("head distance computed");
#endif

    head_distance=0; //Reuse variable to compute mean head distance

    //Use mean distance of last measured head distances
    for(unsigned int i=0;i<head_distances_.size();i++)
    	head_distance+=head_distances_[i];

    head_distance=head_distance/head_distances_.size();

	//ROS_ERROR ("HEAD DISTANCE AFTER MEAN COMPUTING: %f",head_distance);


#ifdef marco_debug
	ROS_INFO("updated undetected count");
#endif
	if(head_distance != head_distance) //not a number
		head_distance=3.0;


	//Create HeadDistance message
	std_msgs::Float32 head_distance_msgs;
	head_distance_msgs.data=head_distance;
	face_distance_pub_.publish(head_distance_msgs);
	//Create Face Pos and Size message
	sensor_msgs::JointState message;
	int servos_count=2;
	message.name.resize(servos_count);
	message.position.resize(servos_count);
	message.velocity.resize(servos_count);

	message.name[0]="head_pan_joint";	//izquierda-derecha

	message.name[1]="head_tilt_joint";	//arriba-abajo

	message.header.stamp = ros::Time::now();
#ifdef marco_debug
	ROS_INFO("message created");
#endif

	if( notFoundCount_ >= 10 )
	{
		float rand_tilt = search_min_tilt_+((search_max_tilt_-search_min_tilt_) * double(rand()%20)/20.);
		float rand_pan = search_min_pan_+((search_max_pan_-search_min_pan_) * double(rand()%20)/20.);
		message.position[0]=rand_pan;
		message.position[1]=rand_tilt;
		message.velocity[0]=search_pan_vel_;
		message.velocity[1]=search_tilt_vel_;
		//ROS_ERROR("RANDOM MOVE: tilt: %f  pan: %f",rand_tilt,rand_pan);
		random_=true;
	}
	else
	{
		if(face_detected_bool_)
		{
			float pan_pos=meas_.at<float>(0); // it was meas_
			float tilt_pos=meas_.at<float>(1);
			pan_pos=scalePan(pan_pos);
			tilt_pos=scaleTilt(tilt_pos);
			message.position[0]=yaw_from_joint_ + pan_pos;
			message.position[1]=pitch_from_joint_ + tilt_pos;
			message.velocity[0]=abs(pan_pos*1.3)  ;
			message.velocity[1]=abs(tilt_pos*1.5);
		}
		else
		{
			float pan_pos=state_.at<float>(0); // it was meas_
			float tilt_pos=state_.at<float>(1);
			pan_pos=scalePan(pan_pos);
			tilt_pos=scaleTilt(tilt_pos);
			message.position[0]=yaw_from_joint_ + pan_pos;
			message.position[1]=pitch_from_joint_ + tilt_pos;
			message.velocity[0]=abs(pan_pos*1.3);
			message.velocity[1]=abs(tilt_pos*1.5);
		}
		//ROS_ERROR("KALMAN MOVE: pan: %f --- tilt: %f",message.position[0], message.position[1]);
		random_=false;
	}

	cv::imshow("Kalman predictor", image_received);
	cvWaitKey(1);



    /*
     * Publish joint state
     */
#ifdef marco_debug
	ROS_INFO("publishing: pan_pos: %lg --- tilt_pos: %lg",message.position[0],message.position[1]);
#endif
	joint_pub_.publish(message);
	//ROS_ERROR("JOint state yaw_from_joint_: %f",yaw_from_joint_);
	sendBaseVelocity(head_distance);

}
Exemple #25
0
int main( int agrc, char** argv )
{
    uint8_t *raw;
    char *filename = argv[1];
    image_width = atoi( argv[2] );
    image_height = atoi( argv[3] );
    printf( "%s %d %d\n", filename, image_width, image_height );
    stride = image_width+2;
    raw = read_raw( filename );
    write_padded( "padded.raw", raw );
    uint8_t *blurred = malloc( stride*(image_height+2)*4 );

    clock_t start = clock();
    /* Box Blur applied 3 times is extremely similar to Gaussian blur */
    for ( int y = 0; y < image_height+2; y++ )
    {
        for ( int x = 0; x < stride; x++ )
        {
            average_neighbors( raw, blurred, x, y );
        }
    }
    for ( int y = 0; y < image_height+2; y++ )
    {
        for ( int x = 0; x < stride; x++ )
        {
            average_neighbors( blurred, blurred, x, y );
        }
    }
    for ( int y = 0; y < image_height+2; y++ )
    {
        for ( int x = 0; x < stride; x++ )
        {
            average_neighbors( blurred, blurred, x, y );
        }
    }
    clock_t end = clock();
    float seconds = (float)(end - start) / CLOCKS_PER_SEC;
    printf( "Regular box blur took %f seconds\n", seconds );
    write_raw( "blurred.raw", blurred );

    start = clock();
    memset( blurred, 0, stride*(image_height+2)*4 );
    /* Box Blur applied 3 times is extremely similar to Gaussian blur */
    for ( int y = 0; y < image_height+2; y++ )
    {
        for ( int x = 0; x < stride; x+=2 )
        {
            average_neighbors_simd( raw, blurred, x, y );
        }
    }
    for ( int y = 0; y < image_height+2; y++ )
    {
        for ( int x = 0; x < stride; x+=2 )
        {
            average_neighbors_simd( blurred, blurred, x, y );
        }
    }
    for ( int y = 0; y < image_height+2; y++ )
    {
        for ( int x = 0; x < stride; x+=2 )
        {
            average_neighbors_simd( blurred, blurred, x, y );
        }
    }
    end = clock();
    seconds = (float)(end - start) / CLOCKS_PER_SEC;
    printf( "SIMD blur took %f seconds\n", seconds );
    write_raw( "blurred_simd.raw", blurred );

    start = clock();
    memset( blurred, 0, stride*(image_height+2)*4 );
    for ( int y = 0; y < image_height+2; y++ )
    {
        for ( int x = 0; x < stride; x++ )
        {
            grayscale( raw, blurred, x, y );
        }
    }
    end = clock();
    seconds = (float)(end - start) / CLOCKS_PER_SEC;
    printf( "grayscale took %f seconds\n", seconds );
    write_raw( "grayscale.raw", blurred );

    start = clock();
    memset( blurred, 0, stride*(image_height+2)*4 );
    for ( int y = 0; y < image_height+2; y++ )
    {
        for ( int x = 0; x < stride; x+=8 )
        {
            grayscale_simd( raw, blurred, x, y );
        }
    }
    end = clock();
    seconds = (float)(end - start) / CLOCKS_PER_SEC;
    printf( "grayscale SIMD took %f seconds\n", seconds );
    write_raw( "grayscale_simd.raw", blurred );

    start = clock();
    memset( blurred, 0, stride*(image_height+2)*4 );
    for ( int y = 0; y < image_height+2; y++ )
    {
        for ( int x = 0; x < stride; x++ )
        {
            sharpen( raw, blurred, x, y );
        }
    }
    end = clock();
    seconds = (float)(end - start) / CLOCKS_PER_SEC;
    printf( "sharpen took %f seconds\n", seconds );
    write_raw( "sharpen.raw", blurred );

    start = clock();
    memset( blurred, 0, stride*(image_height+2)*4 );
    for ( int y = 0; y < image_height+2; y++ )
    {
        for ( int x = 0; x < stride; x++ )
        {
            sharpen_simd( raw, blurred, x, y );
        }
    }
    end = clock();
    seconds = (float)(end - start) / CLOCKS_PER_SEC;
    printf( "sharpen SIMD took %f seconds\n", seconds );
    write_raw( "sharpen_simd.raw", blurred );

    free( raw );
    free( blurred );
    return 0;
}
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // canvas
    imageLabel = new QLabel("Загрузите изображение");
    imageLabel->setBackgroundRole(QPalette::Dark);

    ui->scrollArea->setWidget(imageLabel);

    imageLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    imageLabel->setBackgroundRole(QPalette::Base);

    // layouts
    ui->centralWidget->setLayout(ui->mainLayout);
    ui->scrollArea->setBackgroundRole(QPalette::Dark);

    ui->toolsDock->setWidget(ui->toolsScrollArea);
    ui->toolsLayout->setMargin(10);
    ui->toolsScrollAreaContent->setLayout(ui->toolsLayout);

    ui->brightnessDock->setWidget(ui->brightnessScrollArea);
    ui->brightnessLayout->setMargin(10);
    ui->brightnessScrollAreaContents->setLayout(ui->brightnessLayout);

    ui->filtersDock->setWidget(ui->filtersScrollArea);
    ui->filtersLayout->setMargin(5);
    ui->filtersScrollArea->setLayout(ui->filtersLayout);

    ui->multiTab->setLayout(ui->multiLayout);
    ui->multiLayout->setMargin(10);

    ui->additTab->setLayout(ui->additLayout);
    ui->additLayout->setMargin(10);

    ui->impulseTab->setLayout(ui->impulseLayout);
    ui->impulseLayout->setMargin(10);

    ui->analysisTab->setLayout(ui->analysisLayout);
    ui->analysisLayout->setMargin(10);

    ui->autolevelsGroupBox->setLayout(ui->autolevelsLayout);
    ui->linContrastGroupBox->setLayout(ui->linContrastLayout);
    //ui->autolevelsLayout->setMargin(5);

    ui->brightnessDock->hide();
    // signals & slots
    connect(ui->loadButton, SIGNAL(clicked()), this, SLOT(loadImage()));

    connect(ui->showToolsAction,      SIGNAL(toggled(bool)),     ui->toolsDock,      SLOT(setShown(bool)));
    connect(ui->showBrightnessAction, SIGNAL(toggled(bool)),     ui->brightnessDock, SLOT(setShown(bool)));

    connect(ui->showProcessedButton,  SIGNAL(clicked()),         this, SIGNAL(restoreImage()));
    connect(ui->noiseDial,            SIGNAL(valueChanged(int)), this, SIGNAL(rateChanged(int)));
    connect(ui->filterOffsetBox,      SIGNAL(valueChanged(int)), this, SIGNAL(offsetChanged(int)));
    connect(ui->actionGrayscale,      SIGNAL(triggered()),       this, SIGNAL(grayscale()));
    connect(ui->histAction,           SIGNAL(triggered()),       this, SIGNAL(showHist()));
    connect(ui->invertseAction,       SIGNAL(triggered()),       this, SIGNAL(inverse()));
    connect(ui->equalizeAction,       SIGNAL(triggered()),       this, SIGNAL(equalize()));

    // test
    connect(ui->showConvolutionAction, SIGNAL(toggled(bool)), ui->filtersDock, SLOT(setShown(bool)));

    ui->collectionsTab->setLayout(ui->collectionsLayout);
    ui->collectionsLayout->setMargin(5);

    this->resize(1000, 600);
    this->move(50, 50);
    this->raise();
}
Exemple #27
-1
ImageRAII canny( IplImage * image, std::pair< int, int > thresh, double sigma )
{
	const char * WINDOW_NAME = "Basic Canny Edge Detector";

	ImageRAII grayscale( cvCreateImage( cvGetSize( image ), image->depth, 1 ) );
	ImageRAII destination( cvCreateImage( cvGetSize( image ), image->depth, grayscale.image->nChannels ) );
	ImageRAII gaussian( cvCreateImage( cvGetSize( image ), image->depth, grayscale.image->nChannels ) );
	ImageRAII gradient_x( cvCreateImage( cvGetSize( image ), image->depth, grayscale.image->nChannels ) );
	ImageRAII gradient_y( cvCreateImage( cvGetSize( image ), image->depth, grayscale.image->nChannels ) );
	ImageRAII gradient( cvCreateImage( cvGetSize( image ), image->depth, grayscale.image->nChannels ) );
	ImageRAII orientation( cvCreateImage( cvGetSize( image ), image->depth, grayscale.image->nChannels ) );

	// convert image to grayscale
	cvCvtColor( image, grayscale.image, CV_BGR2GRAY );

	// gaussian smoothing
	cvSmooth( grayscale.image, gaussian.image, CV_GAUSSIAN, GAUSSIAN_X, GAUSSIAN_Y, sigma );
	// find edge strength
	cvSobel( gaussian.image, gradient_x.image, 1, 0, 3 );
	cvSobel( gaussian.image, gradient_y.image, 0, 1, 3 );
	// find edge orientation
	CvSize image_size = cvGetSize( gaussian.image );

	for( int i = 0; i < image_size.width; i++ )
	{
		for( int j = 0; j < image_size.height; j++ )
		{
			double x = cvGet2D( gradient_x.image, j, i ).val[0];
			double y = cvGet2D( gradient_y.image, j, i ).val[0];
			float angle;

			if( x == 0 )
			{
				if( y == 0 )
					angle = 0;
				else
					angle = 90;
			}
			else
				angle = cvFastArctan( y, x );

			CvScalar g;
			CvScalar a;
		   	g.val[0] = cvSqrt( pow( x, 2 ) + pow( y, 2 ) );
			a.val[0] = find_angle( angle );

			cvSet2D( destination.image, j, i, g );
			cvSet2D( orientation.image, j, i, a );
		}
	}

	ImageRAII suppressed_image = nonMaxSup( destination.image, orientation.image );
	ImageRAII hysteresis_image = hysteresis( suppressed_image.image, orientation.image, thresh );

	cvNamedWindow( WINDOW_NAME );
	cvShowImage( WINDOW_NAME, destination.image );
	cvMoveWindow( WINDOW_NAME, image_size.width, 0 );

	return hysteresis_image;
}