C API
起因
做生物图象处理, 先用python, 速度实在太慢, 用c 选图像库, ImageMagic看上去不错. 可惜, 文档实在太简洁了, 好在open source, 看着源码摸索着走.
开端
ImageMagic的C API有两种, MagickWand 和 MagickCore , Manual两种API都有一个例子程序. MagickCore是一个低阶的API, 但是更灵活, 将仔细讨论. 读取图像, 计算RGB分量的联合分布R-G , G-B, B-R:
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <time.h>
5 #include <magick/ImageMagick.h>
6
7 int main(int argc,char **argv)
8 {
9 ExceptionInfo
10 exception;
11
12 Image
13 *image,
14 *rgimage,
15 *gbimage,
16 *brimage;
17
18 ImageInfo
19 *image_info;
20 char
21 * infilename,
22 * rgfilename,
23 * gbfilename,
24 * brfilename;
25 PixelPacket * ipix, *rgpix,*gbpix, *brpix;
26
27 unsigned char M[3][256*256];
28 unsigned char r,g,b;
29
30 infilename = argv[1];
31 rgfilename = argv[2];
32 gbfilename = argv[3];
33 brfilename = argv[4];
34
35 int i,j;
36
37 /*
38 Initialize the image info structure and read an image.
39 */
40 InitializeMagick(*argv);
41 GetExceptionInfo(&exception);
42 image_info=CloneImageInfo((ImageInfo *) NULL);
43
44 (void) strcpy(image_info->filename, infilename);
45 image=ReadImage(image_info,&exception);
46 if (exception.severity != UndefinedException)
47 CatchException(&exception);
48 if (image == (Image *) NULL)
49 exit(1);
50 /*
51 Turn the images into a thumbnail sequence.
52 */
53
54 fprintf(stderr, "\nImage Info:\n"
55 "name: %s\n"
56 "colorspace : %d\n"
57 "type : %d\n"
58 "columns: %ld rows : %ld\n"
59 "depth: %ld colors: %ld\n"
60 ,
61 image_info->filename,
62 image->colorspace,
63 GetImageType(image, &exception),
64 image->columns,
65 image->rows,
66 image->depth,
67 image->colors
68 );
69
70 ipix = AcquireImagePixels(image, 0, 0,
71 image->columns ,image->rows,
72 &exception);
73 fprintf(stderr, "\ncounting ... \n");
74 memset(M,0,sizeof(M));
75 for(i=0; i < image->columns*image->rows ; i++)
76 {
77 r = ScaleQuantumToChar(ipix[i].red);
78 g = ScaleQuantumToChar(ipix[i].green);
79 b = ScaleQuantumToChar(ipix[i].blue);
80 //if(i%100<10) fprintf(stderr, "(%d,%d,%d)\n", r,g,b);
81 M[0][r*256 + g] < 255 ? M[0][r*256 + g] += 1:0;
82 M[1][g*256 + b] < 255 ? M[1][g*256 + b] += 1:0;
83 M[2][b*256 + r] < 255 ? M[2][b*256 + r] += 1:0;
84 }
85
86 fprintf(stderr, "Writeing file...\n");
87 rgimage = ConstituteImage(256,256,"I",CharPixel,M[0],&exception);
88 gbimage = ConstituteImage(256,256,"I",CharPixel,M[1],&exception);
89 brimage = ConstituteImage(256,256,"I",CharPixel,M[2],&exception);
90
91 fprintf(stderr, "Writeing file: %s\n", rgfilename);
92 (void) strcpy(rgimage->filename, rgfilename);
93 WriteImage(image_info, rgimage);
94 fprintf(stderr, "Writeing file: %s\n", gbfilename);
95 (void) strcpy(gbimage->filename, gbfilename);
96 WriteImage(image_info, gbimage);
97 fprintf(stderr, "Writeing file: %s\n", brfilename);
98 (void) strcpy(brimage->filename, brfilename);
99 WriteImage(image_info, brimage);
100
101 image_info=DestroyImageInfo(image_info);
102
103 DestroyExceptionInfo(&exception);
104 DestroyMagick();
105 return(0);
106 }