我的A程序有问题。我一直在努力搜索问题,但似乎找不到我可以使用的注释。我对C很陌生,所以我尽力去学。
当我尝试使用./imgconvert.c
运行它时,会出现以下错误:
./imgconvert.c: line 6: struct: command not found
./imgconvert.c: line 7: uint8_t: command not found
./imgconvert.c: line 8: syntax error near unexpected token `}'
./imgconvert.c: line 8: `};'
我试着将程序编译成类似于
myProgram.o
然后gcc -c imgconvert.c -o myProgram.o
。但是我得到了一个权限错误,如果我用chmod修复了这个错误,那么我得到了这个错误:bash: ./myProgram.o: cannot execute binary file
我不知道该怎么办?
代码:
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct pixel {
uint8_t r, g, b, a;
};
static uint8_t *load_image(char *filename, int *sizex, int *sizey)
{
uint8_t *image;
char buf[512];
char *bufptr;
int ret;
FILE *fp = fopen(filename, "r");
bufptr = fgets(buf, 512, fp);
ret = fscanf(fp, "%d %d\n", sizex, sizey);
bufptr = fgets(buf, 512, fp);
image = malloc(*sizex * *sizey * 4);
int i;
uint8_t *ptr = image;
for (i=0; i<*sizex * *sizey; ++i) {
ret = fread(ptr, 1, 3, fp);
ptr += 4;
}
fclose(fp);
return image;
}
static int save_image(const char *filename, uint8_t *image, int sizex, int sizey)
{
FILE *fp = fopen(filename, "w");
fprintf(fp, "P6\n%d %d\n255\n", sizex, sizey);
int i;
uint8_t *ptr = image;
for (i=0; i<sizex * sizey; ++i) {
fwrite(ptr, 1, 3, fp);
ptr += 4;
}
fclose(fp);
return 1;
}
void convert_grayscale(uint8_t *input, uint8_t *output, int sizex, int sizey)
{
// Y = 0.299 * R + 0.587 * G + 0.114 * B
int i;
for (i = 0; i < sizex * sizey; ++i)
{
struct pixel *pin = (struct pixel*) &input[i*4];
struct pixel *pout = (struct pixel*) &output[i*4];
float luma = 0.299 * pin->r + 0.587 * pin->g + 0.114 * pin->b;
if (luma > 255)
luma = 255;
uint8_t intluma = (int) luma;
pout->r = intluma;
pout->g = intluma;
pout->b = intluma;
pout->a = 255;
}
}
int main()
{
uint8_t *inputimg, *outputimg;
int sizex, sizey;
inputimg = load_image("image.ppm", &sizex, &sizey);
outputimg = malloc(sizex * sizey * 4);
convert_grayscale(inputimg, outputimg, sizex, sizey);
save_image("output.ppm", outputimg, sizex, sizey);
}
最佳答案
你眼前的问题是C程序必须被编译和链接。gcc调用使用-c
选项,该选项告诉它只执行“编译”部分。试试看吧
gcc -g -Wall imgconvert.c -o imgconvert
然后
./imgconvert
我添加了一些新选项,
-g
意味着生成调试信息,-Wall
意味着启用所有在默认情况下应该启用但没有启用的警告。我没有详细查看您的代码,但很可能您将从第一个命令中收到一些“warning:”消息,您应该修复这些消息。使用
-c
选项,您得到的是一个“object”文件(这就是“.o”的意思),它只作为后续链接操作的输入有用。当你开始编写比一个文件大得多的程序时,你会想要这样。顺便说一句,当您试图直接执行c源代码时,出现的错误是因为,由于为向后兼容保留了古老的默认值,shell尝试执行任何不可识别为已编译可执行文件(在文件开头
\177ELF
)或正确标记为已解释脚本(在开头#! /path/to/interpreter
)的内容就好像是一个shell脚本。关于c - 在C中将图像转换为黑白时出现问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20105904/