Пример #1
0
int get_img(int fp,u8 *buf)
{

    int fd;

    int buffer_size;
    //    struct timeval starttime,endtime;
    //    fp=fp;
    //打开framebuffer设备

    buffer_size = (WIDTH * HEIGHT * BITS_PER_FB/8);

    //获取一帧数据

    if(read(fd,trgb,buffer_size) < 0)
    {
        printf("reaf failed!\n");
        return 0;
    }
    //格式转换
    //    gettimeofday(&endtime,0);
    RGB565_to_RGB24(trgb,buf,WIDTH,HEIGHT);
    //    gettimeofday(&starttime,0);


    //jpeg压缩
    if(jpeg_compress(buf,WIDTH,HEIGHT)<0)
        printf("compress failed!\n");

    //    double timeuse = 1000000*(endtime.tv_sec - starttime.tv_sec) + endtime.tv_usec - starttime.tv_usec;

    //    printf("timeuse=%f\n",timeuse);

    return 0;
}
Пример #2
0
/**
  * @brief  Save the image frame into a file
  * @param  Storage path
  * @param  file_name: Jpeg file name
  * @retval Status 
  */
static uint8_t Save_Jpg_To_File (uint8_t *path , uint8_t *file_name)
{
  RTC_TimeTypeDef   RTC_TimeStructure;
  RTC_DateTypeDef   RTC_DateStructure;
  FIL file;

  /* Update file name */
  strcpy((char *)ImageBuffer.ImageName , (char *)path),
  strcat ((char *)ImageBuffer.ImageName, "/");

  if ( RTC_Error == 0)
  {
    RTC_GetTime(RTC_Format_BIN, &RTC_TimeStructure);
    RTC_GetDate(RTC_Format_BIN, &RTC_DateStructure);

    sprintf((char *)file_name, "Camera_%02d%02d%d%02d%02d%02d.jpg", RTC_DateStructure.RTC_Date,
            RTC_DateStructure.RTC_Month,
            RTC_DateStructure.RTC_Year + 2000,
            RTC_TimeStructure.RTC_Hours,
            RTC_TimeStructure.RTC_Minutes,
            RTC_TimeStructure.RTC_Seconds);
  }
  else
  {
    sprintf((char *)file_name, "Camera_%08d.jpg", (int)(RecoveryImageCounter++));
  }

  strcat ((char *)ImageBuffer.ImageName, (char *)file_name);
  /* Can not create file */
  if (f_open(&file, (char *)ImageBuffer.ImageName, FA_CREATE_NEW | FA_WRITE) != FR_OK)
  {
    return 0;
  }

  /* Convert RGB16 image to RGB24 */
  RGB16toRGB24(ImageBuffer.DestData, ImageBuffer.RawData , 1);

  /* Set compression parameters */

  jpeg_params.in_buff = (uint8_t *)ImageBuffer.DestData;
  jpeg_params.in_length = IMAGE_COLUMN_SIZE * IMAGE_LINE_SIZE * 3;
  jpeg_params.in_width = IMAGE_LINE_SIZE;
  jpeg_params.in_height = IMAGE_COLUMN_SIZE;
  jpeg_params.in_bpp = 3;
  jpeg_params.in_colorspace = JCS_RGB;
  jpeg_params.in_imagequality = 100;

  jpeg_compress(&file, &jpeg_params);

  /* Close file */
  f_close(&file);
  return 1 ;
}
Пример #3
0
static mp_obj_t py_image_threshold(mp_obj_t image_obj, mp_obj_t color_list_obj, mp_obj_t threshold)
{
    color_t *color;
    image_t *image;

    /* sanity checks */
    PY_ASSERT_TRUE(sensor.pixformat == PIXFORMAT_RGB565);
    PY_ASSERT_TRUE(sensor.framesize <= FRAMESIZE_QCIF);

    /* read arguments */
    image = py_image_cobj(image_obj);
    int thresh = mp_obj_get_int(threshold);

    /* returned image */
    image_t bimage = {
        .w=image->w,
        .h=image->h,
        .bpp=1,
        .pixels=image->data+(image->w*image->h*image->bpp)
    };

    /* copy color list */
    uint len;
    mp_obj_t *color_arr;
    mp_obj_get_array(color_list_obj, &len, &color_arr);

    color = xalloc(len*sizeof*color);

    for (int i=0; i<len; i++) {
        mp_obj_t *color_obj;
        mp_obj_get_array_fixed_n(color_arr[i], 3, &color_obj);
        color[i].r = mp_obj_get_int(color_obj[0]);
        color[i].g = mp_obj_get_int(color_obj[1]);
        color[i].b = mp_obj_get_int(color_obj[2]);
    }

    /* Threshold image using reference color */
    imlib_threshold(image, &bimage, color, len, thresh);

    return py_image_from_struct(&bimage);
}

static mp_obj_t py_image_rainbow(mp_obj_t src_image_obj)
{
    image_t *src_image = NULL;

    /* get C image pointer */
    src_image = py_image_cobj(src_image_obj);
    /* sanity checks */
    PY_ASSERT_TRUE(src_image->bpp==1);

    image_t dst_image = {
        .w=src_image->w,
        .h=src_image->h,
        .bpp=2,
        .pixels=xalloc(src_image->w*src_image->h*2)
    };

    imlib_rainbow(src_image, &dst_image);
    *src_image = dst_image;
    return src_image_obj;
}

static mp_obj_t py_image_compress(mp_obj_t image_obj, mp_obj_t quality)
{
    image_t *image = py_image_cobj(image_obj);

    image_t cimage = {
        .w=image->w,
        .h=image->h,
        .bpp=0,
        .pixels= NULL
    };

    jpeg_compress(image, &cimage, mp_obj_get_int(quality));
    return py_image_from_struct(&cimage);
}

static mp_obj_t py_image_draw_line(mp_obj_t image_obj, mp_obj_t line_obj)
{
    /* get image pointer */
    struct image *image;
    image = py_image_cobj(image_obj);

    mp_obj_t *array;
    mp_obj_get_array_fixed_n(line_obj, 4, &array);
    int x0 = mp_obj_get_int(array[0]);
    int y0 = mp_obj_get_int(array[1]);
    int x1 = mp_obj_get_int(array[2]);
    int y1 = mp_obj_get_int(array[3]);

    imlib_draw_line(image, x0, y0, x1, y1);
    return mp_const_none;
}

static mp_obj_t py_image_draw_circle(mp_obj_t image_obj, mp_obj_t c_obj, mp_obj_t r_obj)
{
    int cx, cy, r;
    mp_obj_t *array;

    struct image *image;
    color_t c = {.r=0xFF, .g=0xFF, .b=0xFF};

    /* get image pointer */
    image = py_image_cobj(image_obj);

    /* center */
    mp_obj_get_array_fixed_n(c_obj, 2, &array);
    cx = mp_obj_get_int(array[0]);
    cy = mp_obj_get_int(array[1]);

    /* radius */
    r = mp_obj_get_int(r_obj);
    imlib_draw_circle(image, cx, cy, r, &c);
    return mp_const_none;
}

static mp_obj_t py_image_draw_string(uint n_args, const mp_obj_t *args)
{
    int x = mp_obj_get_int(args[1]);
    int y = mp_obj_get_int(args[2]);
    image_t *image =py_image_cobj(args[0]);
    const char *str = mp_obj_str_get_str(args[3]);
    color_t c = {.r=0xFF, .g=0xFF, .b=0xFF};

    if (n_args == 5) {
        // get color
        mp_obj_t *array;
        mp_obj_get_array_fixed_n(args[4], 3, &array);
        c.r = mp_obj_get_int(array[0]);
        c.g = mp_obj_get_int(array[1]);
        c.b = mp_obj_get_int(array[2]);
    }
    imlib_draw_string(image, x, y, str, &c);
    return mp_const_none;
}


static mp_obj_t py_image_erode(mp_obj_t image_obj, mp_obj_t ksize_obj)
{
    image_t *image = NULL;
    image = py_image_cobj(image_obj);

    /* sanity checks */
    PY_ASSERT_TRUE(image->bpp==1);

    imlib_erode(image, mp_obj_get_int(ksize_obj));
    return mp_const_none;
}
Пример #4
0
int main(int argc, char **argv) {
    int err;
    int myrank, numprocs;
    double inicio, fim;
    FILE * inputFiles[argc - 1];
    char **arquivos[argc - 1];
    char nomeArquivos[30][256];
    char nomeArquivosJPG[30][256];
    char nomeArquivosRAW[30][256];
    char nomeArquivosCINZA[30][256];

    if (argc != 2) {
        printf("Número de Parâmetros incorreto. Use: mpirun -np <QTD_PROCESSOS> ./build/jpeg2raw <QTD_IMAGENS>\n");
        err = -1;
        goto error;
    }
    int QTD_IMAGENS = atoi(argv[1]);

    //armazena a quantidade de imagens ainda a serem processadas
    int imagensRestantes = QTD_IMAGENS;
    int imagensProcessadas = 0;
    int controle;
    int acabou = 0; // [0=false,1=true]

    MPI_Status status;
    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
    MPI_Comm_size(MPI_COMM_WORLD, &numprocs);

    inicio = MPI_Wtime();

    int z;
    char str1[40], str2[10], strJPG[40], strRAW[40], strCINZA[40];

    controle = numprocs;

    if ((numprocs - 1) > QTD_IMAGENS) {
        printf("Bah, você está disperdiçando recursos...\n");
        controle = QTD_IMAGENS;
    }

    //Armazena o nome das Imagens a serem processadas
    for (z = 1; z <= QTD_IMAGENS; z++) {
        strcpy(str1, "images/montage");
        sprintf(str2, "%d", z);
        strcat(str1, str2);
        //printf("[str]%s\n", str1);

        strncpy(strJPG, str1, sizeof (str1));
        strncpy(strRAW, str1, sizeof (str1));
        strncpy(strCINZA, str1, sizeof (str1));

        strcpy(nomeArquivos[z], str1);
        strcpy(nomeArquivosJPG[z], strcat(strJPG, ".jpg"));
        strcpy(nomeArquivosRAW[z], strcat(strRAW, ".raw"));
        strcpy(nomeArquivosCINZA[z], strcat(strCINZA, "cinza.jpg"));
    }
    printf("################################################### \n");
    printf("Número de Processos: %d \n", numprocs);
    printf("Imagens a serem processadas: \n");
    for (z = 1; z <= QTD_IMAGENS; z++) {
        printf("%s\n", nomeArquivos[z]);
    }
    printf("################################################### \n");


    for (z = 1; z <= QTD_IMAGENS; z++) {
            printf("\n[%d]Processando a Imagem %s\n", myrank, nomeArquivosJPG[z]);
            struct raw_img raw_img;
            err = 0;
            FILE *jpeg_file;
            struct jpeg_decompress_struct jdec;
            struct jpeg_error_mgr jerr;
            JSAMPROW row_pointer[1];
            float r;
            float g;
            float b;
            int i;
            int j;
            j = 0;

            /**
             * abre um arquivo JPEG no espaço de cores RGB e extrai a luminância  
             * (imagem em tons de cinza), que é gravada em um arquivo especificado pelo usuário.
             */
            const char *file = argv[1];
            struct raw_img *raw = &raw_img;

            //err = jpeg_decompress(argv[1], &raw_img, myrank, numprocs);

            //carrega o arquivo de imagem jpeg
            jpeg_file = fopen(nomeArquivosJPG[z], "rb");
            if (jpeg_file == NULL) {
                printf("Error opening file %s\n!", nomeArquivosJPG[z]);
                err = -1;
                goto error;
            }

            jdec.err = jpeg_std_error(&jerr);
            jpeg_create_decompress(&jdec);
            jpeg_stdio_src(&jdec, jpeg_file);
            jpeg_read_header(&jdec, TRUE);

            raw->width = jdec.image_width;
            raw->height = jdec.image_height;
            raw->num_comp = jdec.num_components;

            if (raw->num_comp != 3) {
                printf("Cannot convert a jpeg file with %d componentes per "
                        "pixel\n", raw->num_comp);
                err = -1;
                goto error;
            }

            //INFORMAÇÕES DA IMAGEM
            //printf("JPEG File Information:\n");
            printf("Resolução: %d x %d pixels\n", raw->width, raw->height);
            //printf("\tColor components per pixel: %d\n", raw->num_comp);

            jpeg_start_decompress(&jdec);
            raw->img = (uint8_t *) malloc(raw->width * raw->height);
            row_pointer[0] = (unsigned char *) malloc(raw->width * raw->num_comp);

            while (jdec.output_scanline < jdec.image_height) {
                jpeg_read_scanlines(&jdec, row_pointer, 1);
                for (i = 0; i < raw->width * raw->num_comp; i += 3) {
                    r = (float) row_pointer[0][i];
                    g = (float) row_pointer[0][i + 1];
                    b = (float) row_pointer[0][i + 2];
                    /* here convert to grayscale */
                    raw->img[j] = (uint8_t)
                            (0.2126 * r + 0.7152 * g + 0.0722 * b);
                    j++;
                }
            }

            jpeg_finish_decompress(&jdec);
            jpeg_destroy_decompress(&jdec);
            free(row_pointer[0]);
            fclose(jpeg_file);

            if (err == -1)
                goto error;
            //	save_raw_image(argv[2], &raw_img);
            save_raw_image(nomeArquivosRAW[z], &raw_img);
            free(raw_img.img);

            //Convere o RAW para imagem em tons de cinza
            //SERIA o SEGUNDO COMANDO QUE É EXECUTADO
            struct raw_img2 raw_img2;
            err = 0;
            raw_img2.width = raw->width;
            raw_img2.height = raw->height;
            // printf("DEBUG2 widht[%d] height[%d]\n", raw_img2.width, raw_img2.height);

            // err = open_raw_image(argv[1], &raw_img);
            //open_raw_image(const char *file, struct raw_img *raw)
            const char *file2 = nomeArquivosRAW[z];
            struct raw_img2 *raw2 = &raw_img2;
            FILE *raw_file;
            size_t read;
            size_t size;

            //	raw_file = fopen(file2, "r");
            raw_file = fopen(file2, "r");
            if (raw_file == NULL) {
                printf("Could not open '%s' file\n", file2);
                err = -1;
                goto error;
            }
            // printf("Abriu arquivo RAW\n");
            size = raw2->width * raw2->height;
            raw2->img = (uint8_t *) malloc(size * sizeof (uint8_t));
            if (raw2->img == NULL) {
                err = -2;
                goto error;
            }
            read = fread((void *) raw2->img, 1, size, raw_file);
            if (read != size)
                printf("Only %lu/%lu bytes were read\n", read, size);

            fclose(raw_file);

            if (err == -1)
                goto error;
            if (err == -2)
                goto error;
            jpeg_compress(nomeArquivosCINZA[z], &raw_img2);
        }
    
        fim = MPI_Wtime();
        printf("TEMPO SEQ[%f].\n", fim - inicio);

        MPI_Finalize();
        return 0;
        //cleanup:
        //	free(raw_img2.img);
error:
        return err;
    }
Пример #5
0
 int main()
 {
 
     int fd;
     struct fb_var_screeninfo fb_var_info;
     struct fb_fix_screeninfo fb_fix_info;
     unsigned char *trgb;
     unsigned char *rgb;
     int buffer_size;
     struct timeval starttime,endtime;
 
     //打开framebuffer设备
     fd = open("/dev/fb0",O_RDONLY);
     if(fd < 0)
     {
         printf("can not open dev\n");
         exit(1);
     }
 
     //获取LCD的可变参数
     ioctl(fd,FBIOGET_VSCREENINFO,&fb_var_info);
     //一个像素多少位    
     printf("bits_per_pixel: %d\n",fb_var_info.bits_per_pixel);
     //x分辨率
     printf("xres: %d\n",fb_var_info.xres);
     //y分辨率
     printf("yres: %d\n",fb_var_info.yres);
     //r分量长度(bit)
     printf("red_length: %d\n",fb_var_info.red.length);
     //g分量长度(bit)
     printf("green_length: %d\n",fb_var_info.green.length);
     //b分量长度(bit)
     printf("blue_length: %d\n",fb_var_info.blue.length);
     //t(透明度)分量长度(bit)
     printf("transp_length: %d\n",fb_var_info.transp.length);
     //r分量偏移
     printf("red_offset: %d\n",fb_var_info.red.offset);
     //g分量偏移
     printf("green_offset: %d\n",fb_var_info.green.offset);
     //b分量偏移
     printf("blue_offset: %d\n",fb_var_info.blue.offset);
     //t分量偏移
     printf("transp_offset: %d\n",fb_var_info.transp.offset);
 
     //获取LCD的固定参数
     ioctl(fd,FBIOGET_FSCREENINFO,&fb_fix_info);
     //一帧大小
     printf("smem_len: %d\n",fb_fix_info.smem_len);
     //一行大小
     printf("line_length: %d\n",fb_fix_info.line_length);
 
     //一帧大小
     buffer_size = (fb_var_info.xres * fb_var_info.yres * BITS_PER_FB/8);
 
     trgb = (unsigned char *)malloc(buffer_size);
     if(trgb==NULL)
         exit(0);
     rgb = (unsigned char *)malloc(fb_var_info.xres * fb_var_info.yres * 3);
     if(rgb==NULL)
     {
         goto here;
     }
     //获取一帧数据

     if(read(fd,trgb,buffer_size) < 0)
     {
         printf("reaf failed!\n");
         goto read_fail;
     }
     //格式转换
     gettimeofday(&endtime,0);     
     //     RGB565_to_RGB24(trgb,rgb,fb_var_info.xres,fb_var_info.yres);
     gettimeofday(&starttime,0);


     //jpeg压缩
     if(jpeg_compress(trgb,fb_var_info.xres,fb_var_info.yres)<0)
         printf("compress failed!\n");        

     double timeuse = 1000000*(endtime.tv_sec - starttime.tv_sec) + endtime.tv_usec - starttime.tv_usec;

     printf("timeuse=%f\n",timeuse);
 read_fail:
     free(rgb);
 here:
     free(trgb);
     
 
     close(fd);
 
     return 0;
 }
Пример #6
0
void *
thread(void *arg)
{
	struct fw_ctx *fctx;
	int fd;
	char buf[1024];
	struct image curimg;
	struct grab_ctx idx;
	struct jpegbuf jbuf;
	int ret;
	int cpid;
	char tsfnbuf[1024];
	time_t now;
	struct tm tm;
	
	fctx = ((struct module_ctx *) arg)->custom;
	
	memset(&idx, 0, sizeof(idx));
	for (;;)
	{
		time(&now);
		localtime_r(&now, &tm);
		strftime(tsfnbuf, sizeof(tsfnbuf) - 1, fctx->path, &tm);
		snprintf(buf, sizeof(buf) - 1, "%s.tmp", tsfnbuf);

		filter_get_image(&curimg, &idx, ((struct module_ctx *) arg)->node, NULL);
		jpeg_compress(&jbuf, &curimg, ((struct module_ctx *) arg)->node);
		
		fd = open(buf, O_WRONLY | O_CREAT | O_TRUNC, 0666);
		if (fd < 0)
		{
			log_log(MODNAME, "Open of %s failed: %s\n", buf, strerror(errno));
			goto freesleeploop;
		}
		
		if (fctx->chmod != -1)
			fchmod(fd, fctx->chmod);
		
		ret = write(fd, jbuf.buf, jbuf.bufsize);
		if (ret != jbuf.bufsize)
		{
			log_log(MODNAME, "Write to %s failed: %s\n",
				buf, (ret == -1) ? strerror(errno) : "short write");
			close(fd);
			unlink(buf);
			goto freesleeploop;
		}
		
		close(fd);
		
		if (fctx->cmd)
		{
			cpid = fork();
			if (cpid < 0)
			{
				log_log(MODNAME, "fork() failed: %s\n", strerror(errno));
				unlink(buf);
				goto freesleeploop;
			}
			if (!cpid)
			{
				/* child */
				close(STDIN_FILENO);
				for (fd = 3; fd < 1024; fd++)
					close(fd);
				
				execlp(fctx->cmd, fctx->cmd, buf, NULL);
				
				/* notreached unless error */
				log_log(MODNAME, "exec(\"%s\") failed: %s\n", fctx->cmd, strerror(errno));
				_exit(0);
			}
			
			do
				ret = waitpid(cpid, NULL, 0);
			while (ret == -1 && errno == EINTR);

			ret = access(buf, F_OK);
			if (ret)
				goto freesleeploop;
		}
		
		ret = rename(buf, tsfnbuf);
		if (ret != 0)
		{
			log_log(MODNAME, "Rename of %s to %s failed: %s\n",
				buf, tsfnbuf, strerror(errno));
			unlink(buf);
			goto freesleeploop;
		}
		
freesleeploop:
		free(jbuf.buf);
		image_destroy(&curimg);
		if (fctx->interval > 0)
			sleep(fctx->interval);
		else
		{
			sleep(5);
			log_log(MODNAME, "Negative interval specified, exiting now.\n");
			exit(0);
		}
	}
}
Пример #7
0
static mp_obj_t py_image_threshold(mp_obj_t image_obj, mp_obj_t color_list_obj, mp_obj_t threshold)
{
    color_t *color;
    image_t *image;

    /* sanity checks */
    PY_ASSERT_TRUE_MSG(sensor.pixformat == PIXFORMAT_RGB565,
            "This function is only supported on RGB565 images");

    PY_ASSERT_TRUE_MSG(sensor.framesize <= OMV_MAX_BLOB_FRAME,
            "This function is only supported on "OMV_MAX_BLOB_FRAME_STR" and smaller frames");


    /* read arguments */
    image = py_image_cobj(image_obj);
    int thresh = mp_obj_get_int(threshold);

    /* returned image */
    image_t bimage = {
        .w=image->w,
        .h=image->h,
        .bpp=1,
        .pixels=image->data+(image->w*image->h*image->bpp)
    };

    /* copy color list */
    uint len;
    mp_obj_t *color_arr;
    mp_obj_get_array(color_list_obj, &len, &color_arr);

    color = xalloc(len*sizeof*color);

    for (int i=0; i<len; i++) {
        mp_obj_t *color_obj;
        mp_obj_get_array_fixed_n(color_arr[i], 3, &color_obj);
        color[i].r = mp_obj_get_int(color_obj[0]);
        color[i].g = mp_obj_get_int(color_obj[1]);
        color[i].b = mp_obj_get_int(color_obj[2]);
    }

    /* Threshold image using reference color */
    imlib_threshold(image, &bimage, color, len, thresh);

    return py_image_from_struct(&bimage);
}

static mp_obj_t py_image_rainbow(mp_obj_t src_image_obj)
{
    image_t *src_image = NULL;

    /* get C image pointer */
    src_image = py_image_cobj(src_image_obj);

    /* sanity checks */
    PY_ASSERT_TRUE_MSG(src_image->bpp == 1,
            "This function is only supported on GRAYSCALE images");

    image_t dst_image = {
        .w=src_image->w,
        .h=src_image->h,
        .bpp=2,
        .pixels=xalloc(src_image->w*src_image->h*2)
    };

    imlib_rainbow(src_image, &dst_image);
    *src_image = dst_image;
    return src_image_obj;
}

static mp_obj_t py_image_compress(mp_obj_t image_obj, mp_obj_t quality)
{
    image_t *image = py_image_cobj(image_obj);

    image_t cimage = {
        .w=image->w,
        .h=image->h,
        .bpp = JPEG_INIT_BUF,
        .pixels = xalloc(JPEG_INIT_BUF)
    };

    jpeg_compress(image, &cimage, mp_obj_get_int(quality));

    return py_image_from_struct(&cimage);
}
Пример #8
0
GLOBAL void
write_JPEG_file (char * filename)
{
  /* These three structs contain JPEG parameters and working data.
   * They must survive for the duration of parameter setup and one
   * call to jpeg_compress; typically, making them local data in the
   * calling routine is the best strategy.
   */
  struct Compress_info_struct cinfo;
  struct Compress_methods_struct c_methods;
  struct External_methods_struct e_methods;

  /* Initialize the system-dependent method pointers. */
  cinfo.methods = &c_methods;	/* links to method structs */
  cinfo.emethods = &e_methods;
  /* Here we use the default JPEG error handler, which will just print
   * an error message on stderr and call exit().  See the second half of
   * this file for an example of more graceful error recovery.
   */
  jselerror(&e_methods);	/* select std error/trace message routines */
  /* Here we use the standard memory manager provided with the JPEG code.
   * In some cases you might want to replace the memory manager, or at
   * least the system-dependent part of it, with your own code.
   */
  jselmemmgr(&e_methods);	/* select std memory allocation routines */
  /* If the compressor requires full-image buffers (for entropy-coding
   * optimization or a noninterleaved JPEG file), it will create temporary
   * files for anything that doesn't fit within the maximum-memory setting.
   * (Note that temp files are NOT needed if you use the default parameters.)
   * You can change the default maximum-memory setting by changing
   * e_methods.max_memory_to_use after jselmemmgr returns.
   * On some systems you may also need to set up a signal handler to
   * ensure that temporary files are deleted if the program is interrupted.
   * (This is most important if you are on MS-DOS and use the jmemdos.c
   * memory manager back end; it will try to grab extended memory for
   * temp files, and that space will NOT be freed automatically.)
   * See jcmain.c or jdmain.c for an example signal handler.
   */

  /* Here, set up pointers to your own routines for input data handling
   * and post-init parameter selection.
   */
  c_methods.input_init = input_init;
  c_methods.get_input_row = get_input_row;
  c_methods.input_term = input_term;
  c_methods.c_ui_method_selection = c_ui_method_selection;

  /* Set up default JPEG parameters in the cinfo data structure. */
  j_c_defaults(&cinfo, 75, FALSE);
  /* Note: 75 is the recommended default quality level; you may instead pass
   * a user-specified quality level.  Be aware that values below 25 will cause
   * non-baseline JPEG files to be created (and a warning message to that
   * effect to be emitted on stderr).  This won't bother our decoder, but some
   * commercial JPEG implementations may choke on non-baseline JPEG files.
   * If you want to force baseline compatibility, pass TRUE instead of FALSE.
   * (If non-baseline files are fine, but you could do without that warning
   * message, set e_methods.trace_level to -1.)
   */

  /* At this point you can modify the default parameters set by j_c_defaults
   * as needed.  For a minimal implementation, you shouldn't need to change
   * anything.  See jcmain.c for some examples of what you might change.
   */

  /* Select the input and output files.
   * Note that cinfo.input_file is only used if your input reading routines
   * use it; otherwise, you can just make it NULL.
   * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
   * requires it in order to write binary files.
   */

  cinfo.input_file = NULL;	/* if no actual input file involved */

  if ((cinfo.output_file = fopen(filename, "wb")) == NULL) {
    fprintf(stderr, "can't open %s\n", filename);
    exit(1);
  }

  /* Here we go! */
  jpeg_compress(&cinfo);

  /* That's it, son.  Nothin' else to do, except close files. */
  /* Here we assume only the output file need be closed. */
  fclose(cinfo.output_file);

  /* Note: if you want to compress more than one image, we recommend you
   * repeat this whole routine.  You MUST repeat the j_c_defaults()/alter
   * parameters/jpeg_compress() sequence, as some data structures allocated
   * in j_c_defaults are freed upon exit from jpeg_compress.
   */
}
Пример #9
0
int main(int argc, char **argv) {
    int err;
    int myrank, numprocs;
    double inicio, fim;
    FILE * inputFiles[argc - 1];
    char **arquivos[argc - 1];
    char nomeArquivos[30][256];
    char nomeArquivosJPG[30][256];
    char nomeArquivosRAW[30][256];
    char nomeArquivosCINZA[30][256];
    
    if (argc != 2) {
        printf("Número de Parâmetros incorreto. Use: mpirun -np <QTD_PROCESSOS> ./build/jpeg2raw <QTD_IMAGENS>\n");
        err = -1;
        goto error;
    }
    int QTD_IMAGENS = atoi(argv[1]);

    //armazena a quantidade de imagens ainda a serem processadas
    int imagensRestantes = QTD_IMAGENS;
    int imagensProcessadas = 0;
    int controle;
    int acabou = 0; // [0=false,1=true]
    printf("ARGS%d", argc);

    MPI_Status status;
    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
    MPI_Comm_size(MPI_COMM_WORLD, &numprocs);

    inicio = MPI_Wtime();

    int z;
    char str1[40], str2[10], strJPG[40], strRAW[40], strCINZA[40];

    controle = numprocs;

    if ((numprocs - 1) > QTD_IMAGENS) {
        printf("Bah, você está disperdiçando recursos...\n");
        controle = QTD_IMAGENS;
    }

    //Armazena o nome das Imagens a serem processadas
    for (z = 1; z <= QTD_IMAGENS; z++) {
        strcpy(str1, "images/montage");
        sprintf(str2, "%d", z);
        strcat(str1, str2);
        //printf("[str]%s\n", str1);

        strncpy(strJPG, str1, sizeof (str1));
        strncpy(strRAW, str1, sizeof (str1));
        strncpy(strCINZA, str1, sizeof (str1));

        strcpy(nomeArquivos[z], str1);
        strcpy(nomeArquivosJPG[z], strcat(strJPG, ".jpg"));
        strcpy(nomeArquivosRAW[z], strcat(strRAW, ".raw"));
        strcpy(nomeArquivosCINZA[z], strcat(strCINZA, "cinza.jpg"));
    }



    if (numprocs > 1) {
        if (myrank == MESTRE) {
            printf("################################################### \n");
            printf("Número de Processos: %d \n", numprocs);
            printf("Imagens a serem processadas: \n");
            for (z = 1; z <= QTD_IMAGENS; z++) {
                printf("%s\n", nomeArquivos[z]);
            }
            printf("################################################### \n");
            

            //Envia para os primeiros processos
            int tag = 0;
            int x;
            for (x = 1; x < controle; x++) {
                MPI_Send(&x, 1, MPI_INT, x, tag, MPI_COMM_WORLD); //tamanho do array
                imagensRestantes--;
                //printf("Imagens Restantes: %d\n", imagensRestantes);
            }
            int destino;
            int retorno;
            int proxima = controle;
            while (imagensRestantes != 0) {
                MPI_Recv(&retorno, 1, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
                imagensProcessadas++;
                destino = status.MPI_SOURCE;
                MPI_Send(&proxima, 1, MPI_INT, status.MPI_SOURCE, tag, MPI_COMM_WORLD); //tamanho do array
                proxima++;
                imagensRestantes--;
            }

            //recebe
            int recebido = 0;
            for (x = 1; x < controle; x++) {
                MPI_Recv(&recebido, 1, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
                imagensProcessadas++;
                //envia código para finalizar os escravos (-1)
                int dados = -1;
                MPI_Send(&dados, 1, MPI_INT, status.MPI_SOURCE, tag, MPI_COMM_WORLD); //finalizacao
            }
            fim = MPI_Wtime();
            printf("TEMPO PARALELO[%f] - Imagens Processadas[%d].\n", fim - inicio, imagensProcessadas);
        } else {
            while (acabou != 1) {
                int posicao;
                // int *arrayReceiving;
                MPI_Recv(&posicao, 1, MPI_INT, 0, MPI_ANY_TAG, MPI_COMM_WORLD, &status);

                if (posicao == -1) {
                    acabou = 1;
                } else {
                    printf("\n[%d]Processando a Imagem %s\n", myrank, nomeArquivosJPG[posicao]);
                    struct raw_img raw_img;
                    err = 0;
                    FILE *jpeg_file;
                    struct jpeg_decompress_struct jdec;
                    struct jpeg_error_mgr jerr;
                    JSAMPROW row_pointer[1];
                    float r;
                    float g;
                    float b;
                    int i;
                    int j;
                    j = 0;

                    /**
                     * abre um arquivo JPEG no espaço de cores RGB e extrai a luminância  
                     * (imagem em tons de cinza), que é gravada em um arquivo especificado pelo usuário.
                     */
                    const char *file = argv[1];
                    struct raw_img *raw = &raw_img;

                    //err = jpeg_decompress(argv[1], &raw_img, myrank, numprocs);

                    //carrega o arquivo de imagem jpeg
                    jpeg_file = fopen(nomeArquivosJPG[posicao], "rb");
                    if (jpeg_file == NULL) {
                        printf("Error opening file %s\n!", nomeArquivosJPG[posicao]);
                        err = -1;
                        goto error;
                    }

                    jdec.err = jpeg_std_error(&jerr);
                    jpeg_create_decompress(&jdec);
                    jpeg_stdio_src(&jdec, jpeg_file);
                    jpeg_read_header(&jdec, TRUE);

                    raw->width = jdec.image_width;
                    raw->height = jdec.image_height;
                    raw->num_comp = jdec.num_components;

                    if (raw->num_comp != 3) {
                        printf("Cannot convert a jpeg file with %d componentes per "
                                "pixel\n", raw->num_comp);
                        err = -1;
                        goto error;
                    }

                    //INFORMAÇÕES DA IMAGEM
                    printf("JPEG File Information:\n");
                    printf("Resolução: %d x %d pixels\n", raw->width, raw->height);
                    //printf("\tColor components per pixel: %d\n", raw->num_comp);

                    jpeg_start_decompress(&jdec);
                    raw->img = (uint8_t *) malloc(raw->width * raw->height);
                    row_pointer[0] = (unsigned char *) malloc(raw->width * raw->num_comp);

                    while (jdec.output_scanline < jdec.image_height) {
                        jpeg_read_scanlines(&jdec, row_pointer, 1);
                        for (i = 0; i < raw->width * raw->num_comp; i += 3) {
                            r = (float) row_pointer[0][i];
                            g = (float) row_pointer[0][i + 1];
                            b = (float) row_pointer[0][i + 2];
                            /* here convert to grayscale */
                            raw->img[j] = (uint8_t)
                                    (0.2126 * r + 0.7152 * g + 0.0722 * b);
                            j++;
                        }
                    }

                    jpeg_finish_decompress(&jdec);
                    jpeg_destroy_decompress(&jdec);
                    free(row_pointer[0]);
                    fclose(jpeg_file);

                    if (err == -1)
                        goto error;
                    //	save_raw_image(argv[2], &raw_img);
                    save_raw_image(nomeArquivosRAW[posicao], &raw_img);
                    free(raw_img.img);

                    //Convere o RAW para imagem em tons de cinza
                    //SERIA o SEGUNDO COMANDO QUE É EXECUTADO
                    struct raw_img2 raw_img2;
                    err = 0;
                    raw_img2.width = raw->width;
                    raw_img2.height = raw->height;
                    // printf("DEBUG2 widht[%d] height[%d]\n", raw_img2.width, raw_img2.height);

                    // err = open_raw_image(argv[1], &raw_img);
                    //open_raw_image(const char *file, struct raw_img *raw)
                    const char *file2 = nomeArquivosRAW[posicao];
                    struct raw_img2 *raw2 = &raw_img2;
                    FILE *raw_file;
                    size_t read;
                    size_t size;

                    //	raw_file = fopen(file2, "r");
                    raw_file = fopen(file2, "r");
                    if (raw_file == NULL) {
                        printf("Could not open '%s' file\n", file2);
                        err = -1;
                        goto error;
                    }
                    // printf("Abriu arquivo RAW\n");
                    size = raw2->width * raw2->height;
                    raw2->img = (uint8_t *) malloc(size * sizeof (uint8_t));
                    if (raw2->img == NULL) {
                        err = -2;
                        goto error;
                    }
                    read = fread((void *) raw2->img, 1, size, raw_file);
                    if (read != size)
                        printf("Only %lu/%lu bytes were read\n", read, size);

                    fclose(raw_file);

                    if (err == -1)
                        goto error;
                    if (err == -2)
                        goto error;
                    jpeg_compress(nomeArquivosCINZA[posicao], &raw_img2);
                    MPI_Send(&err, 1, MPI_INT, 0, 0, MPI_COMM_WORLD);
                }
            }
        }
    } else { //FAZ SEQUENCIAL
        for (z = 1; z <= QTD_IMAGENS; z++) {
            int posicao = z;
            struct raw_img raw_img;

            err = 0;


            FILE *jpeg_file;
            struct jpeg_decompress_struct jdec;
            struct jpeg_error_mgr jerr;
            JSAMPROW row_pointer[1];
            float r;
            float g;
            float b;
            int i;
            int j;
            err = 0;
            j = 0;




            /**
             * abre um arquivo JPEG no espaço de cores RGB e extrai a luminância  
             * (imagem em tons de cinza), que é gravada em um arquivo especificado pelo usuário.
             */
            const char *file = argv[1];
            struct raw_img *raw = &raw_img;

            //err = jpeg_decompress(argv[1], &raw_img, myrank, numprocs);

            //carrega o arquivo de imagem jpeg
            jpeg_file = fopen(nomeArquivosJPG[posicao], "rb");
            //	jpeg_file = fopen(arquivos[1], "rb");
            //        printf("%p\n",jpeg_file);
            //        printf("%s\n",jpeg_file);
            if (jpeg_file == NULL) {
                printf("Error opening file %s\n!", nomeArquivosJPG[posicao]);
                err = -1;
                goto error;
            }

            jdec.err = jpeg_std_error(&jerr);
            jpeg_create_decompress(&jdec);
            jpeg_stdio_src(&jdec, jpeg_file);
            jpeg_read_header(&jdec, TRUE);


            raw->width = jdec.image_width;
            raw->height = jdec.image_height;
            raw->num_comp = jdec.num_components;

            printf("[DEBUG] WIDTH[%d] HEIGHT[%d] COMP[%d]\n", jdec.image_width, jdec.image_height, jdec.num_components);
            printf("[DEBUG] WIDTH[%d] HEIGHT[%d] COMP[%d]\n", raw->width, raw->height, raw->num_comp);

            if (raw->num_comp != 3) {
                printf("Cannot convert a jpeg file with %d componentes per "
                        "pixel\n", raw->num_comp);
                err = -1;
                goto error;
            }

            //        int altura = raw->height;
            //        int partes = raw->height/(numprocs-1); //desconta 1 por causa do mestre
            //        int resto = raw->height%(numprocs-1);  //desconta 1 por causa do mestre
            //        printf("Altura %u \n", altura);
            if (myrank == MESTRE) {
                //            printf("raw->height %.f \n",raw->height/numprocs);
                //            printf("Altura %u \n", altura);
                //            printf("Processos %d Divisão %d \n", numprocs, partes);
                //            printf("Resto %u \n", resto);
                //INFORMAÇÕES DA IMAGEM
                printf("JPEG File Information:\n");
                printf("\tResolution: %d x %d pixels\n", raw->width, raw->height);
                printf("\tColor components per pixel: %d\n", raw->num_comp);
            } else {
                //            printf("Sou o processo[%d] e vou calculdar de [%d - %d]\n", myrank, ((myrank-1)*partes), (myrank*partes));
            }

            jpeg_start_decompress(&jdec);

            raw->img = (uint8_t *) malloc(raw->width * raw->height);
            row_pointer[0] = (unsigned char *) malloc(raw->width * raw->num_comp);

            printf("\t raw->width * raw->num_comp: %d\n", raw->width * raw->num_comp);


            while (jdec.output_scanline < jdec.image_height) {
                jpeg_read_scanlines(&jdec, row_pointer, 1);
                //                #pragma omp parallel for
                //                #pragma omp for schedule(static) ordered
                //                 #pragma omp parallel
                // {
                //                 #pragma omp for schedule(static) ordered
                //                 #pragma omp for ordered private(i,j)
                for (i = 0; i < raw->width * raw->num_comp; i += 3) {
                    r = (float) row_pointer[0][i];
                    g = (float) row_pointer[0][i + 1];
                    b = (float) row_pointer[0][i + 2];
                    /* here convert to grayscale */
                    //                        #pragma omp ordered 
                    //                        #pragma omp critical
                    //                        {
                    raw->img[j] = (uint8_t)
                            (0.2126 * r + 0.7152 * g + 0.0722 * b);
                    j++;
                    //                        }
                    //		}
                }
            }
            printf("J %d \n", j);

            jpeg_finish_decompress(&jdec);
            jpeg_destroy_decompress(&jdec);
            free(row_pointer[0]);
            fclose(jpeg_file);

            if (err == -1)
                goto error;
            //	save_raw_image(argv[2], &raw_img);
            save_raw_image(nomeArquivosRAW[posicao], &raw_img);
            free(raw_img.img);


            //Convere o RAW para imagem em tons de cinza
            //SERIA o SEGUNDO COMANDO QUE É EXECUTADO
            struct raw_img2 raw_img2;
            err = 0;
            //	if (argc != 5) {
            //		printf("Usage: %s <raw_file> <jpeg> <width> <height>\n",argv[0]);
            //		err = -1;
            //		goto error;
            //	}

            raw_img2.width = raw->width;
            raw_img2.height = raw->height;
            printf("DEBUG2 widht[%d] height[%d]\n", raw_img2.width, raw_img2.height);

            // err = open_raw_image(argv[1], &raw_img);
            //open_raw_image(const char *file, struct raw_img *raw)
            const char *file2 = nomeArquivosRAW[posicao];
            struct raw_img2 *raw2 = &raw_img2;
            FILE *raw_file;
            size_t read;
            size_t size;

            //	raw_file = fopen(file2, "r");
            raw_file = fopen(file2, "r");
            if (raw_file == NULL) {
                printf("Could not open '%s' file\n", file2);
                err = -1;
                goto error;
            }
            printf("Abriu arquivo RAW\n");
            size = raw2->width * raw2->height;
            raw2->img = (uint8_t *) malloc(size * sizeof (uint8_t));
            if (raw2->img == NULL) {
                err = -2;
                goto error;
            }
            read = fread((void *) raw2->img, 1, size, raw_file);
            if (read != size)
                printf("Only %lu/%lu bytes were read\n", read, size);

            fclose(raw_file);

            if (err == -1)
                goto error;
            if (err == -2)
                goto error;
            jpeg_compress(nomeArquivosCINZA[posicao], &raw_img2);
        }
        fim = MPI_Wtime();
        printf("TEMPO SEQ[%f].\n", fim - inicio);
    }
    // fim = MPI_Wtime();

    MPI_Finalize();
    return 0;
    //cleanup:
    //	free(raw_img2.img);
error:
    return err;
}