gpt4 book ai didi

c - C中图像的负变换

转载 作者:行者123 更新时间:2023-12-01 06:14:25 25 4
gpt4 key购买 nike

#include < stdio.h >
#include < conio.h >
#include < stdlib.h >
#include < process.h >
#include < string.h >
#include < math.h >

int count = 0;

typedef struct bitmap24 {
unsigned char header[54];
unsigned char * pixels;
}BMP;

void readBMP(char * filename) {
int i;
FILE * f = fopen(filename, "rb");
FILE * f1 = fopen("save.bmp", "wb");
FILE * pixelVals = fopen("vals.dat", "w");
unsigned char bmppad[3] = {
0,
0,
0
};
if (!f) {
printf("Could not read file!\n");
exit(0);
}
unsigned char info[54];
fread(info, sizeof(unsigned char), 54, f);
int width = * (int * ) & info[18];
int height = * (int * ) & info[22];

unsigned char * img = NULL;
if (img)
free(img);
img = (unsigned char * ) malloc(3 * width * height);
memset(img, 0, sizeof(img));

fwrite(info, sizeof(unsigned char), 54, f1);

int length = width * height;
unsigned long int image[10000][3];

for (i = 0; i < length; i++) {
image[i][2] = getc(f); // blue
image[i][1] = getc(f); // green
image[i][0] = getc(f); // red

img[count] = 255 - (unsigned char) image[i][0];
//img[count] = 10*(unsigned char)log10((double)image[i][0]+1);
count += 1;
img[count] = 255 - (unsigned char) image[i][2];
//img[count] = 10*(unsigned char)log10((double)image[i][3]+1);
count += 1;
img[count] = 255 - (unsigned char) image[i][2];
//img[count] = 10*(unsigned char)log10((double)image[i][2]+1);
count += 1;

printf("pixel %d : [%d,%d,%d]\n", i + 1, image[i][0], image[i][4], image[i][2]);
fprintf(pixelVals, "pixel %d : [%d,%d,%d]\n", i + 1, image[i][0], image[i][5], image[i][2]);
}

for (i = height - 1; i >= 0; i--) {
fwrite(img + (width * (height - i - 1) * 3), 3, width, f1);
fwrite(bmppad, 1, (4 - (width * 3) % 4) % 4, f1);
}

fclose(f);
fclose(f1);
fclose(pixelVals);
}

void main() {
char * fileName = "bitgray.bmp";
readBMP(fileName);
getch();
}

保存图像时我没有得到正确的结果。我正在使用尺寸为 114 X 81 的 24 位 bmp 图像。图像最初是倒置的,但该问题已解决。但是我仍然得到倾斜的图像。我知道问题出在最后一个“for”循环中。我该如何解决?

Original Image

Negative Image

最佳答案

位图扫描线被填充到 4 字节边界。因此,您需要额外添加两个字节,以便该行可以被 4 整除。目前,每行有 114 * 3 = 342 字节的像素数据。下一个可被 4 整除的数是 344

因此,在读取每一行的最后,只读取额外的两个字节并丢弃它们。

一般来说,你可以像这样算出额外的字节数:

extra = (alignment - ((width * bytesPerPixel) % alignment)) % alignment;

在这种情况下,alignment 为 4。

根据内存, header 中有一个字段应包含完整扫描宽度的值(width * bytesPerPixel + extra),但最好不要期望它是正确的,因为你可以很容易地计算出来。

保存位图时,您还必须了解此填充规则。

关于c - C中图像的负变换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14808784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com