1、结构体数组的优点
结构体可以存储不同的数据类型,将他们互相联系起来。结构体数组可以连续存储多个结构体,和数组作用相似。比如想定义同一个最小外接矩形的四个坐标值,并给予这个矩形一个特征编号。当需要存储多个最小外接矩形的信息时,就需要动态申请一个结构体数组。
2、结构体数组的定义和使用
以某一个需求为例,给出了结构体数组的定义、初始化、用户交互使用、释放。
struct rect //待检测区域的结构体
{int min_x; //左上坐标int min_y;int max_x; //右下坐标int max_y;char feature; //特征编号:A 泡棉 B 标签 C Logo
};
struct rect *area = (rect*)malloc(sizeof(rect) * area_num); //动态申请area_num个结构体数组,存储待检测区域信息if (area == NULL){printf("Fail to allocate memory to area\n");//cout << "Fail to allocate memory to rect1" << endl;exit(1);}for (int k = 0; k < area_num; k++)//初始化{area[k].min_x = 0;area[k].max_x = 0;area[k].min_y = 0;area[k].max_y = 0;area[k].feature = 0;}printf("请依次输入待检测区域坐标和待检测的特征\n");printf("坐标为左上坐标和右下坐标,特征编号为:A 泡棉 B 标签 C logo 各个数据空格隔开输入\n");for (int i = 0; i < area_num; i++){scanf("%d %d %d %d %c", &area[i].min_x, &area[i].min_y, &area[i].max_x, &area[i].max_y, &area[i].feature);}
for (int i = 0; i < area_num; i++)//循环截取判断{int rect_width = area[i].max_x - area[i].min_x + 1;int rect_height = area[i].max_y - area[i].min_y + 1;unsigned char *mindst = (unsigned char*)malloc(rect_width* rect_height* sizeof(unsigned char));unsigned char *minsrc = (unsigned char*)malloc(rect_width* rect_height* sizeof(unsigned char));cutout(gray2, minsrc, widths, heights, &area[i] );//基准图截取cutout(dst, mindst, widths, heights, &area[i] );//结果图截取printf("区域序号:%d :",i);switch (area[i].feature){case 'A': //泡棉检测{float result_jz01;float result_jz02;result_jz01 = calGLCM(minsrc, GLCM_ANGLE_VERTICAL, rect_width, rect_height);result_jz02 = calGLCM(mindst, GLCM_ANGLE_VERTICAL, rect_width, rect_height);printf("一致性差值 = %f\n", abs(result_jz01 - result_jz02));if (abs(result_jz01 - result_jz02) > 600) //阈值可调节printf("贴泡棉\n");elseprintf("未贴泡棉\n");break;};case 'B': //标签检测{float result_ssim;result_ssim = SSIM(minsrc, mindst, rect_width, rect_height);printf("相似性 = %f\n", abs(result_ssim));if (result_ssim > 0.4) //阈值可调节printf("贴标签\n");elseprintf("未贴标签\n");break;};case 'C': //logo检测{float result_ssim;result_ssim = SSIM(minsrc, mindst, rect_width, rect_height);printf("相似性 = %f\n", abs(result_ssim));if (result_ssim > 0.4) //阈值可调节printf("LOGO正确\n");elseprintf("LOGO不正确\n");break;};default: printf("未输入特征类型!");}free(mindst);free(minsrc);}
free(area);//一定要释放