2015-12-01 7 views
-1

Я видел на google, это было о делении на ноль, но я не вижу, где или только в том случае, когда d = 0 и * l < = 0,5 ... (строка 15) Это функция преобразования RGB значения пиксела из файла JPEG, в значениях HSL (Hue, Saturation, Luminance)Может кто-нибудь понять, почему у меня есть исключение с плавающей запятой?

#include <stdio.h> 
float rgbToHsl(int r1, int g1, int b1, float *h, float *s, float *l){ 

    float r = r1; 
    float g = g1; 
    float b = b1; 
    r/=255; g /= 255; b/=255; 
    int max = maximum(r, g, b); 
    int min = minimum(r, g, b); 
    *l = (max + min)/2; 

    if (max == min) 
     *h = *s = 0; // achromatique 
    else{ 
     int d = max - min; 
     *s = *l > 0.5 ? d/(2 - max - min) : d/(max + min); 
     if (max == r) 
      *h = (g-b)/d + (g < b ? 6 : 0); 
     if (max == g) 
      *h = (b-r)/d + 2; 
     if (max == b) 
      *h = (r-g)/d + 4; 

     /*case r: *h = r; 
      case g: *h = g; 
      case b: *h = b; */ 
    } 
    *h /= 6; 
    //printf("r: %f, g : %f, b : %f",r,g,b); 

return *h; 



} 

int maximum (int a, int b, int c){ 
    if (a > b){ 
     if (a > c) 
      return a; 
     else 
      return c; 
    } 
    else{ 
     if (b > c) 
      return b; 
     if (c > b) 
      return c; 
    } 
} 

int minimum (int a, int b, int c){ 
    if (a < b){ 
     if (a < c) 
      return a; 
     else 
      return c; 
    } 
    else{ 
     if (b < c) 
      return b; 
     if (c < b) 
      return c; 
    } 


} 

спасибо ребята

EDIT: добавлен остальную часть моего проекта, как вы спросили: это о преобразовании РГБ в файл jpeg в HSL:

main.c:

#include <stdio.h> 
#include <stdlib.h> 
#include <jpeglib.h> 
#include "fonctions.h" 


int main (int argc, char** argv){ 


    int H; 
    int W; 
    int C; 
    FILE *fichier = NULL; //file pour l'image entrée 
    FILE *image = NULL; //file pou l'image à la sortie 
    JSAMPARRAY buffer; //buffer où sera contenue l'image 

    buffer = malloc(256*(sizeof(char))); 

    if (argv[1] == NULL) 
     fichier = fopen("cara.jpg", "r"); 
    else 
     fichier = fopen(argv[1], "r"); 
    image = fopen("cara_image_cree.jpg", "wb"); 

    if (fichier == NULL) 
     printf("Probleme lecture"); 

    printf("Cara Delevingne\n"); 
    buffer = lire(fichier, &H, &W, &C); 

    /* afficher 3 sous-pixels : 
    printf("\nBuffer case 1 : %d", buffer[0][0]); 
    printf("\nBuffer case 1 : %d", buffer[0][0+1]); 
    printf("\nBuffer case 1 : %d\n", buffer[0][0+2]);*/ 
    ecrire(&H, &W, &C, buffer, image); 
     printf("Cara222\n"); 
     fflush(stdout); 
    fclose(fichier); 
    fclose(image); 
    return 0; 
} 

read.c:

#include <stdlib.h> 
#include <stdio.h> 
#include <errno.h> 
#include <jpeglib.h> 
#include <jerror.h> 
#include "fonctions.h" 

JSAMPARRAY lire (FILE* file, int *H, int *W, int *C){ 

    struct jpeg_decompress_struct cinfo; 
    struct jpeg_error_mgr jerr; 

    int n = 0; 
    JSAMPARRAY buffer; // buffer qui va contenir l'image 

    /*printf("SHITSHITSHITSHITDEBUG\n"); 
     fflush(stdout);*/ 
    cinfo.err = jpeg_std_error(&jerr); 
    jpeg_create_decompress(&cinfo); // Initialisation de la structure 

    jpeg_stdio_src(&cinfo,file); // file est de type FILE * (descripteur de fichier 
    // sur le fichier jpeg a decompresser) 
    jpeg_read_header(&cinfo,TRUE);// lecture des infos sur l'image jpeg 


    jpeg_start_decompress(&cinfo);// lancement du processus de decompression 


    *H = cinfo.output_height; // on récupère la hauteur 
    *W = cinfo.output_width; // on récupère la largeur 
    *C = cinfo.output_components; // on regarde si l'image est en couleurs ou N&B 

    buffer=(JSAMPARRAY) malloc((*H) *sizeof(JSAMPARRAY)); // on alloue de la mémoire au buffer selon le nb de lignes de pixels qu'il va devoir prendre 
              // éventuellement remplacer par unsigned char** et caster en JSAMPARRAY ou uchar** 

    while (n < (*H)) // tant que le compteur n'a pas dépassé l'image 
    { 
     buffer[n] = (unsigned char*) malloc((*W)*(*C)*sizeof(char)); // on alloue à chaque ligne, la taille de la largeur 
     /*printf("CARA44 n : %d\n", n); 
     fflush(stdout);*/ 
     jpeg_read_scanlines(&cinfo,buffer+n,1); // lecture des n lignes suivantes de l'image 
     // dans le buffer (de type unsigned char *) 
     n++; 
    } 

    jpeg_finish_decompress(&cinfo); 

    jpeg_destroy_decompress(&cinfo); 

    return buffer; 
} 

write.c:

#include <stdlib.h> 
#include <stdio.h> 
#include <errno.h> 
#include <jpeglib.h> 
#include <jerror.h> 
#include "fonctions.h" 



void ecrire (unsigned int *H, unsigned int *W, unsigned int *C, JSAMPARRAY buffer, FILE *file){ 

    struct jpeg_compress_struct cinfo; 
    struct jpeg_error_mgr jerr; 

    float* bufferHSL; 
    unsigned char* verif; 
    int n = 0; // parcoureurs pour écrire l'image 

    int i = 0; // parcoureurs pour transformer en HSL 
    int j = 0; 
    int k = 0; 

    float h = 1; // variables pour stocker le résultat HSL 
    float s = 0; 
    float l = 0; 
    float v = 2.83223244; 
    int r, g, b; 

    int e = 0; // variables de vérification 
    int f = 0; 
    cinfo.err = jpeg_std_error(&jerr); 
    jpeg_create_compress(&cinfo); // Initialisation de la structure 

    jpeg_stdio_dest(&cinfo,file); // file est de type FILE * (descripteur de fichier 
    // sur le fichier jpeg compressé final) 
    cinfo.image_width= *W;   // nombre de ligne de l'image 
    cinfo.image_height= *H;   // nombre de pixel par ligne 
    cinfo.input_components = *C;  // 3 pour une image couleur, 1 pour une N&B 
    cinfo.in_color_space= JCS_RGB; 
    // JCS_GRAYSCALE pour une image N&B 
    jpeg_set_defaults(&cinfo); // initialisation des paramètres de compression 
    jpeg_start_compress(&cinfo,TRUE); // lancement du processus de decompression 

    bufferHSL = (float *) malloc((*H)*(*W) *(*C)*sizeof(long int)); 
    verif = (char*)malloc((*H)*(*W) *(*C) *sizeof(char)); 
    while (i < *H-3){ 
     j = 0; 
     while (j < *W-3) { // lecture des lignes pour transformation HSL  
       //bufferHSL[j] = (float*)malloc((*W) *sizeof(long int)); 
       r = buffer[i][j]; 
       g = buffer[i][j+1]; 
       b = buffer[i][j+2]; 
       //printf("Valeur du buffer : %d\n", buffer[i][j]); 
       //printf("r: %d, g : %d, b : %d\n",r,g,b); 
       rgbToHsl(r, g, b, &h, &s, &l); // converting the red blue green pixels into HSL 
       bufferHSL[k] = h; 
       bufferHSL[k+1] = s; 
       bufferHSL[k+2] = l; 
       //printf("Valeur de hsl : h=%f s=%f l=%f \n", h,s,l); 
       k=k+3; 
       j=j+3; 
     } 
     i++; 
    } 
    printf("coucou"); 

    verif = convhsl2rgb(bufferHSL, *W, *H); //converting back the jpeg in HSL into rgb for verification. 

    k = 0; 

    while(e < *H){ //Double while for putting the unsign char* buffer into unsigned char** bc JSAMPARRAY is uchar ** 
     f = 0; 
     while (f < *W){ 
      //printf("Valeur de hsl : %f et buffer : %d\n", bufferHSL[k], buffer[e][f]); 
      buffer[e][f] = verif[k]; 
      f++; 
      k++; 
     } 
     e++; 

    } 



    while (n < *H) 
    { 
     jpeg_write_scanlines(&cinfo,buffer+n,1);// écriture des n lignes suivantes de l'image 
     // stockées dans le buffer (de type unsigned char *) 
     n++; 
    } 

    jpeg_finish_compress(&cinfo); 

    jpeg_destroy_compress(&cinfo); 

} 

это Alll

+0

Так что происходит, когда '* l> 0,5' и' max + min == 2'? – szczurcio

+1

Не нужно угадывать. Просто запустите свою программу в отладчике. – kaylum

+0

да я думаю, что это будет крах слишком szczurcio, но пока это не произойдет в этой картинке, но да yo'ure право так я добавил это: \t \t если ((макс-мин) == d) \t \t \t макс ++; , так что он заканчивается, но моя фотография выебанная в конце (первая третья часть черно-белой и как деформированная) yea kaylum я никогда не использовал отладчик, но я думаю, что я собираюсь попробовать –

ответ

0

Я думаю, что вы сделали ошибку в функции максимального и минимум. В предложении else у вас есть 2 if: s вместо if-else. У вас возникают проблемы, когда b == c. Точнее, вы можете вернуться без явного оператора return.

int maximum (int a, int b, int c) 
{ 
    if (a > b) { 
     if (a > c) 
      return a; 
     else 
      return c; 
    } else { 
     if (b > c) 
      return b; 
     else 
      return c; 
    } 
} 
+0

да, я видел, я видел его после, и я исправил его np thanks (я изменил каждый int в float), но теперь у меня нормальные значения L, но все H находятся в -inf и при 0 i не понимаю, почему, код адаптирован из псевдокода, данного моим учителем, поэтому алгоритм правильный, но, возможно, это ошибка типа или что-то в этом роде: http://pastebin.com/R8xRyg6a –

+0

Глядя на ваш паштет (pastebin.com/R8xRyg6a), все еще есть ошибка. Попробуйте это чтобы добавить некоторые справки, чтобы увидеть, что у вас есть логическая ошибка. Что-то вроде этого http://pastebin.com/At3KxJGw – raphexion

+0

yea np thx теперь он работает –