C language realizes dynamic memory allocation and release of one or two-D array and image linear interpolation amplification and optimization

Source: Internet
Author: User
Tags function prototype rand intel pentium
1.1 Preface

1. This article is the blogger in an open-minded attitude to learn and communicate with you, Bowen will inevitably have the wrong place, I hope everyone corrected;
2. This article is aimed at the C language and image amplification of the basic discussion, as Daniel can directly ignore this article;
3. Operating environment: Due to different computer configuration and operating time differences in the system, the program's Test platform: computer CPU for Intel Pentium Dual-core E6500, 2.93GHZ memory 4GB. Virtual machine for 10.0 version of the Vmware,linux system for FEDORA16

To talk about the speed of the program, or from the bottom of the computer implementation as the starting point, the following image twice times linear amplification argument this fact. Just contact image processing, to complete the image of twice times linear amplification, the thought of the image has a long and wide, the first thought of using a two-dimensional array to achieve, each interpolation using time complexity of O (n^2) of the two for loop to achieve, insert a few times the value of OK. When you are done, the master said the program also has the optimization of space, because the computer memory when a one-dimensional continuous space, if the start of the use of one-dimensional array to achieve, the effect will be better, 2 times the value of the OK, and each interpolation using the time complexity of O (n). At the same time, it involves the dynamic memory allocation of one-dimensional array and two-dimensional array in the heap, as well as the parameters of one array and two dimensional array as functions.

Theme: The use of interlaced column insertion, the left and right and the upper and lower mean to enlarge the image of 640x480 twice times, into a 1280x960 image, testing the operating efficiency of the program to choose a slightly larger data, the effect will be more obvious. 2.1 Interpolation function parameter is two-dimensional array


The purple box of the circle represents the original data, first up and down the mean interpolation (√), and then take the mean interpolation (x), and then take four mean interpolation (※), and finally insert the last column and the last line. Data from the computer generated pseudo-random number, in order to facilitate testing of the program, to switch to a larger resolution 2048x1536 (Reality did not see this resolution, according to the ratio of 4:3 assigned value, test can be) program from the Linux platform test, the format may have some chaos.

The source code is as follows:

#include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #include <sys/ time.h> typedef unsigned short dbyte;//images each pixel is double-byte (double char), and both are greater than 0; Char is 8bit,short 16bit, and short to represent double char #define H. 1536//Represents the height of the image resolution #define W 2048//The width of the image resolution int interpolation_expansion (Dbyte **original_data, Dbyte **processed_data
    //interpolation function declaration int main (int argc, int *argv[]) {int I, J;
    Dbyte **input_data, **output_data;
        Memory allocation Input_data = (Dbyte *) malloc (h*sizeof (Dbyte *))//For two-dimensional array H row allocate dbyte* memory for (i = 0; i < H; i++) {
    Input_data[i] = (Dbyte *) malloc (w*sizeof (Dbyte));//How many dbyte elements should be stored in each row memset (input_data[i],0,w);//Initialize Memory
        } Output_data = (dbyte * *) malloc (2*h*sizeof (Dbyte *));
        for (i = 0; i < 2*h i++) {Output_data[i] = (Dbyte *) malloc (2*w*sizeof (dbyte));
        memset (OUTPUT_DATA[I],0,2*W); for (i = 0;i < H; i++) {for (j = 0; J < W; J + +) {Input_data[i][j] = rand ();//data using pseudo-random number}} for (I = 238; I < 241;
        i++) {for (j = 324; J < J + +) printf ("[%d][%d]_%d", I, J, Input_data[i][j]);
    printf ("\ n");
    struct Timeval tpstart, tpend;
    float Timeuse;
    Gettimeofday (&tpstart, NULL);//Gets the time before the function call Interpolation_expansion (Input_data, output_data); Gettimeofday (&tpend, NULL);//time to get the end of the function call printf ("_________________________<_________>_________________      
    ________\n "); for (i = 476 i < 481, i++) {for (j = 640; J < 648; J +) printf ("[%d]
                [%d]_%d ", I, J, Output_data[i][j]);
        printf ("\ n");
  }//Calculate the time spent by the function call, the unit is seconds Timeuse = 1000000* (tpend.tv_sec-tpstart.tv_sec) + tpend.tv_usec-tpstart.tv_usec;
  Timeuse/= 1000000;

    printf ("The Usetime two-dimensional array is%fs\n", timeuse); Free memory, "as if notUse the Loop direct free (input_data) Also, if you need to know the second dimension, I am not quite sure "for" (i = 0; i < H; i++) (input_data[i);
    for (i = 0; i < 2*h. i++) {free (output_data[i));
    } int interpolation_expansion (Dbyte **original_data, Dbyte **processed_data)//interpolation function prototype {int i, J;
    int last_line = 2*h-1;
    int last_column = 2*w-1;

    Short Tmp_data; Set values for expansion array inserts the pixel data of the original picture into the picture that needs to be enlarged (subscript [even] [numbered] labeled 0) for (i = 0;i < H; i++) {for (j = 0; J < W;
        J + +) {Processed_data[2*i][2*j] = original_data[i][j]; }//insert values into this subscript is odd line caculating by the up number and down number to insert the upper and lower mean values with known values (subscript [even] [odd
        Number] for (i = 1; i < 2* (H-1) i + + 2)//height_line {for (j = 0;j < 2*w; j = 2)//width_column           
        {Processed_data[i][j] = (Processed_data[i-1][j] + processed_data[i+1][j])/2; }}//insert values into that subscript are odd column caculating by left number and right number to mean insertion (subscript [odd] [even] Mark X) for (i = 0; i < 2*h; i + 2)//heig

                        Ht_line {for (j = 1;j < 2* (W-1); j + + 2)//width_column {
                PROCESSED_DATA[I][J] = (Processed_data[i][j-1] + processed_data[i][j+1])/2; }//insert values into that both weight and height are odd numbers the surrounding four mean values (subscript [odd] [odd] marked ※) for (i = 1; I & Lt 2* (H-1); i + + 2)//height_line {for (j = 1; J < 2* (W-1); j = 2) {Processed_data[i][j] = (proc

        ESSED_DATA[I-1][J-1] + processed_data[i-1][j+1] + processed_data[i+1][j-1] + processed_data[i+1][j+1])/4; }//insert values into the final line and column are interpolated for (i = 0; i< 2*h-1 i++)//insert values in
        To-Last Colum {if (Tmp_data = 2*processed_data[i][last_column-1]-processed_data[i][last_column-2]) >0) {Processed_data[i][last_coLumn] = Tmp_data;  
        else {Processed_data[i][last_column] = processed_data[i][last_column-1]; for (j = 0; j< 2*w-1 + +)//insert values into the last line {if (Tmp_data = 2*processe D_DATA[LAST_LINE-1][J]-processed_data[last_line-2][j]) > 0) {processed_data[last_line][j] = Tmp_
        Data
        }else {Processed_data[last_line][j] = processed_data[last_line-1][j]; }} Processed_data[last_line][last_column] = (Processed_data[last_line-1][last_column] + processed_data[last_line][
    LAST_COLUMN-1] + processed_data[last_line-1][last_column-1])/3;
return 1; }

This program realizes the transfer of function parameter to two-dimensional array, and the dynamic memory allocation of two-dimensional array in the heap. I had directly allocated space on the stack for two-dimensional arrays, that is, to specify rows and columns of dead two-dimensional arrays, but when the resolution was high, the Linux compilation could pass, but the run encountered a segment error (spit core), as follows

At present, the root cause is not found, and the dynamic memory allocation of two-dimensional arrays is used to solve the problem. test results for 2.2 programs


The intercepted data is a block of data in the center of the image before and after the magnification, with an average elapsed time of 0.098260 seconds and 3.1 interpolation function parameters as one-dimensional array


The Circle of the purple box represents the original data, 2 for loop implementations, first of all take the mean value interpolation (x), and then up and down the mean value interpolation (√), but also in the interpolation of the child function to implement dynamic memory, but in order to facilitate management, as far as possible in the main function allocation, who with whom to allocate and release, only need to call the function

The source code is as follows:

#include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #include <sys/
time.h> typedef unsigned short dbyte; #define M 1536///original picture height #define N 2048//Original picture width #define H 3072//height magnified twice times the height of the picture #define W 4096//weight magnified twice times the picture's

Width dbyte* insert_values (dbyte *original_data, Dbyte *processed_data);
     int main (int argc, int *argv[]) {int I, count;
    Memory allocation Dbyte *original_data = (Dbyte *) malloc (m*n*sizeof (dbyte));
    Dbyte *processed_data = (Dbyte *) malloc (w*h*sizeof (dbyte));
        if (Original_data = NULL) {printf ("Please allocate the input memery again!\n");
    } if (Processed_data = NULL) {printf ("Please allocate the output memery again!\n");
        }//Initialize memory to zero memset (original_data,0,m*n);

    memset (PROCESSED_DATA,0,W*H);
    The test program as the follows.
  Set original data for (i = 0; i < n*m; i++) {Original_data[i] = rand ();  }//printf have not being to insert for (i = 238*n +, count = 1; i < 324 + 241* N;)
        {printf ("%d__%ld", I, original_data[i]);
            if (count%4 = = 0) {count = 1;
            i + = (N-3);
        printf ("\ n");
            }else{count++;
        i++;            

    } printf ("______________*****************_____________________________*****************__________\n");
    struct Timeval tpstart, tpend;
    float Timeuse;
    Gettimeofday (&tpstart, NULL);

    Insert_values (original_data,processed_data);//use of the function gettimeofday (&tpend, NULL);
        printf insert have been down for (i = 476*w + 640, Count = 1; i < 648 + 481* W;)
                {printf ("%d__%ld", I, processed_data[i]);
                        if (count%8 = = 0) {count = 1;
                        i + = (W-7);
        printf ("\ n");        }else{count++;
                i++;
    } Timeuse = 1000000* (tpend.tv_sec-tpstart.tv_sec) + tpend.tv_usec-tpstart.tv_usec; 
    Timeuse/= 1000000;
    printf ("The Usetime of one-dimensional array is%fs\n", timeuse);
    Free (processed_data);
Free (original_data);   
    } dbyte* insert_values (Dbyte *original_data, dbyte *processed_data)//the value of return can is define by yourself {
    int I, J;
    Short tmp; Set_values from Original_data to the processed_data for (i = j = 0; i<w* (H-1); i + + 2, j + +)//i for loops to enlarge the image, Step 2 (Compartment insert) , j is used to iterate through the raw data {if (i!= 0) && (i%w) = = 0) to determine whether a W-width of the data inserted, really jump W data continue interpolation, note: If you do not add i!=0, when i=0, only Judge i%w=
        =0, when the first W data is not {i = W;
    } Processed_data[i] = Original_data[j]; //insert_values into the line caculating the mean interpolation for (i = 1;i < w* (H-1); i = = 2) {if ((i+1)%w = = 0)//Last column interpolation method, the image extends from left to right {if ((TMP = processed_data[i-1]*2-processed_data[i-2]) > 0)///If the median is twice times greater than
            The sum of the two values, insert twice times the median value minus the known value {processed_data[i] = tmp;
            else{Processed_data[i] = processed_data[i-1];//If the value you want to insert is less than 0, copy the previous pixel data directly}
        i + W;

        else {Processed_data[i] = (Processed_data[i-1] + processed_data[i+1])/2;
    }//insert_values into the line caculating by up number and down number for (i = W; i < w*h; i++)
            {if (I < w* (H-1)) {Processed_data[i] = (Processed_data[i-w] + processed_data[i+w])/2;
            if ((i+1)%w = = 0) {i = = W;
            }else//the last line of interpolation method, the image extends from top to bottom {if ((TMP = processed_data[i-w]*2-processed_data[i-2*w]) > 0)
            {Processed_data[i] = tmp;
       }else{         Processed_data[i] = processed_data[i-w];
}} return processed_data; }
3.2 test results for one-dimensional array program


The intercepted data is a block of data in the middle of the front and back of the image, with an average running time of 0.081015 seconds and 4.1 conclusions .

(0.098260-0.081015) = 0.17245 seconds
0.17245/0.09826*100=17.55%, efficiency increased by 17.55. Some people may feel that there is no need, after all, now the CPU processing speed is quite fast. But if it is on the embedded device is not necessarily, after all, embedded equipment resources are limited, so very valuable, make full use of it is kingly.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.