1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
| #include <stdio.h>
#define WIDTH 8 #define HEIGHT 6
void display_image(int image[HEIGHT][WIDTH]) { for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { if (image[i][j] == 0) { printf(". "); } else { printf("* "); } } printf("\n"); } }
void invert_image(int image[HEIGHT][WIDTH]) { for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { image[i][j] = 1 - image[i][j]; } } }
void flip_horizontal(int image[HEIGHT][WIDTH]) { for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH / 2; j++) { int temp = image[i][j]; image[i][j] = image[i][WIDTH - 1 - j]; image[i][WIDTH - 1 - j] = temp; } } }
void flip_vertical(int image[HEIGHT][WIDTH]) { for (int i = 0; i < HEIGHT / 2; i++) { for (int j = 0; j < WIDTH; j++) { int temp = image[i][j]; image[i][j] = image[HEIGHT - 1 - i][j]; image[HEIGHT - 1 - i][j] = temp; } } }
int count_foreground_pixels(int image[HEIGHT][WIDTH]) { int count = 0; for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { if (image[i][j] == 1) { count++; } } } return count; }
int main() { int image[HEIGHT][WIDTH] = { {0, 0, 0, 0, 0, 0, 0, 0}, {0, 1, 1, 1, 1, 1, 0, 0}, {0, 1, 0, 0, 0, 1, 0, 0}, {0, 1, 0, 1, 0, 1, 0, 0}, {0, 1, 0, 0, 0, 1, 0, 0}, {0, 1, 1, 1, 1, 1, 0, 0} }; int choice; do { printf("\n=== 图像处理菜单 ===\n"); printf("1. 显示图像\n"); printf("2. 反转图像\n"); printf("3. 水平翻转\n"); printf("4. 垂直翻转\n"); printf("5. 统计前景像素\n"); printf("0. 退出\n"); printf("请选择:"); scanf("%d", &choice); switch (choice) { case 1: printf("\n当前图像:\n"); display_image(image); break; case 2: invert_image(image); printf("\n图像已反转\n"); display_image(image); break; case 3: flip_horizontal(image); printf("\n图像已水平翻转\n"); display_image(image); break; case 4: flip_vertical(image); printf("\n图像已垂直翻转\n"); display_image(image); break; case 5: printf("\n前景像素数量:%d\n", count_foreground_pixels(image)); break; case 0: printf("退出程序\n"); break; default: printf("无效选择!\n"); break; } } while (choice != 0); return 0; }
|