s_sat * sat_init(unsigned ch_num) { try; unsigned u; s_sat * sat = NULL; // throw_null((sat = sfire_alloc(sizeof(s_sat), 1, 1))); throw_null((sat = malloc(sizeof(s_sat)))); sat->ch_num = ch_num; sat->proj_ref = NULL; // throw_null((at->pixel = sfire_alloc(sizeof(uint8_t *), 1, ch_num))); throw_null((sat->pixel = malloc(sizeof(uint8_t *) * ch_num))); for(u = 0; u < ch_num; u++) sat->pixel[u] = NULL; catch; sat_destroy(sat); sat = NULL; finally; return sat; }
int sat_save_ch(s_sat * sat, const char * fname, unsigned ch) { try; int ret = 0; unsigned height = sat->height, width = sat->width; GDALDatasetH ds = NULL; throw_null((ds = GDALCreate(drv_tiff, fname, width, height, 1, GDT_Byte, NULL))); throw((GDALSetProjection(ds, sat->proj_ref) == CE_Failure)); throw((GDALSetGeoTransform(ds, sat->gt_coef) == CE_Failure)); throw(GDALDatasetRasterIO(ds, GF_Write, 0, 0, width, height, sat->pixel[ch], width, height, GDT_Byte, 1, NULL, 0, 0, 0) == CE_Failure); catch; ret = -1; finally; if(ds != NULL) GDALClose(ds); return ret; }
CDbMenu::CDbMenu(QWidget * parent, CDB * db, bool is_video) : QMenu(parent) { throw_null(db, "Передан нулевой указатель"); __db = db; __is_video = is_video; connect(this, SIGNAL(triggered(QAction *)), this, SLOT(trigger(QAction *))); }
s_sat * sat_rasterize_copy(s_sat * c_sat, OGRGeometryH geometry) { try; int band = 1; unsigned height, width, height_width; double burn_value = 255; GDALDatasetH ds = NULL; s_sat * sat = NULL; throw_null((sat = sat_init(1))); height = sat->height = c_sat->height; width = sat->width = c_sat->width; height_width = height * width; sat->proj_ref = strdup(c_sat->proj_ref); sat->ch_num = 0; memcpy(sat->gt_coef, c_sat->gt_coef, sizeof(double) * 6); throw_null((sat->pixel[0] = sfire_alloc(sizeof(uint8_t), 1, height_width))); sat->ch_num = 1; throw_null((ds = GDALCreate(drv_r_mem, "", width, height, 1, GDT_Byte, NULL))); throw((GDALSetProjection(ds, sat->proj_ref) == CE_Failure)); throw((GDALSetGeoTransform(ds, sat->gt_coef) == CE_Failure)); throw((GDALRasterizeGeometries(ds, 1, & band, 1, & geometry, NULL, NULL, & burn_value, NULL, NULL, NULL) == CE_Failure)); throw(GDALDatasetRasterIO(ds, GF_Read, 0, 0, width, height, sat->pixel[0], width, height, GDT_Byte, 1, NULL, 0, 0, 0) == CE_Failure); catch; sat_destroy(sat); sat = NULL; finally; if(ds != NULL) GDALClose(ds); return sat; }
void CMainLoop::new_connection() { if(client_sock == NULL) { throw_null(client_sock = server_sock.nextPendingConnection()); connect(client_sock, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(error(QAbstractSocket::SocketError))); connect(client_sock, SIGNAL(readyRead()), this, SLOT(command())); } }
void * alloc(const unsigned type_size, const unsigned dim, ...) { void * mem = NULL; va_list val; const unsigned dim_1 = dim - 1, dim_2 = dim - 2; unsigned u, v, num, size, step, * dim_size; char * pof, * dof, * t_dof; /* Стандартом гарантируется, что sizeof(char) == 1 */ try { throw_null(dim_size = (unsigned *) alloca(dim * sizeof(unsigned)), "Ошибка при выделении памяти"); va_start(val, dim); for(u = 0, size = 0, num = 1; u < dim; u++) { num *= (dim_size[u] = va_arg(val, unsigned)); size += (u == dim_1 ? type_size : sizeof(void *)) * num; } va_end(val); throw_null(mem = malloc(size), "Ошибка при выделении памяти"); for(u = 0, num = 1, dof = (char *) mem; u < dim_1; u++) { num *= dim_size[u]; pof = dof; t_dof = (dof += num * sizeof(void *)); step = (u == dim_2 ? type_size : sizeof(void *)) * dim_size[u + 1]; for(v = 0; v < num; v++, pof += sizeof(void *), t_dof += step) memcpy(pof, & t_dof, sizeof(void *)); } } catch(...) { free(mem); mem = NULL; } return mem; }
vector< vector<CVertex> > CSXFMap::s_height_map::load(const string fname) { unsigned v, u; pnts.clear(); #ifdef EMBEDDED // Ограничение - только для МГК header.width = 1000; header.height = 1000; for(v = 0; v < header.height; v++) { vector<CVertex> row; for(u = 0; u < header.width; u++) row.push_back(CVertex(u, v, 100)); pnts.push_back(row); } #else unsigned t, elem_num; float * p_buf; shared_ptr<float> buf; CFile fl(fname); fl(& header, sizeof(header)); unpack_header(); check(); elem_num = header.height * header.width; buf.reset(new float[elem_num], std::default_delete<float[]>()); p_buf = buf.get(); throw_null(p_buf); fl(p_buf, elem_num * sizeof(float)); CFile::unpack<float>(p_buf, elem_num); for(u = 0, t = 0; u < header.width; u++) { vector<CVertex> col; for(v = 0; v < header.height; v++, t++) col.push_back(CVertex(u, v, p_buf[t])); pnts.push_back(col); } #endif return pnts; }
void CLua::load_module(const QString module_name) { const QString fname = CConfig::module_fname(module_name); CModule * p_module; for(auto & md : modules) if(md.second->fname() == fname) return; throw_null(p_module = new CModule(fname)); modules[p_module->name()] = shared_ptr<CModule>(p_module); }
QString CScriptEngine::load_module(const QString module_fname) { CModule * p_module; if(modules.contains(module_fname)) return modules[module_fname]->name(); throw_null(p_module = new CModule(module_fname), "Не удалось загрузить модуль"); const QString module_name = p_module->name(); modules[module_name] = QSharedPointer<CModule>(p_module); return module_name; }
int main(const int argc, const char * argv[]) { int ret = 0; unsigned u, v, tv, t, res, yes, yes_captcha, test_num = 1000; CCaptcha * captcha = NULL; CClassifier * cl = NULL; try { throw_null((captcha = new CCaptchaBrigade1)); throw_null((cl = train(CLT_BAYES, captcha, 10000, 1000))); for(u = 0, yes = 0, yes_captcha = 0; u < test_num; u++) { yes += (res = test(cl, captcha)); if(res == nic) yes_captcha++; } printf("Right numbers: %u from %u (%lf %%)\nRight captcha: %u from %u (%lf %%)\n\n", yes, test_num * nic, yes * 100 / (double) (test_num * nic), yes_captcha, test_num, yes_captcha * 100 / (double) test_num); } catch(...) { ret = -1; fprintf(stderr, "\n-------> Error <-------\n\n"); } if(captcha != NULL) delete captcha; if(cl != NULL) delete cl; return ret; }
CLua::CLua() { throw_null(state = luaL_newstate()); luaL_openlibs(state); opencv_register(state); // Регистрация биндингов к OpenCV // ############################################################################ // Регистрация функции - обработчика доступа к модулям lua_pushlightuserdata(state, this); lua_pushcclosure(state, CLua::run_module, 1); lua_setglobal(state, "algo"); }
CClassifier * train(EClassifierType clt, CCaptcha * captcha, unsigned train_vec, unsigned test_num) { CClassifier * cl = NULL; try { throw_null((cl = new CClassifier(clt))); unsigned u, v, tv, t, num, yes; Mat train_data(train_vec, dim, CV_32FC1); Mat responses(train_vec, 1, CV_32SC1); for(u = 0; u < train_vec; u++) { num = rand() % 10; Mat img = (* captcha)(num); Mat vc = vec(img); for(t = 0; t < dim; t++) train_data.at<float>(u, t) = vc.at<float>(0, t); responses.at<int>(u, 0) = num; } cl->train(train_data, responses); for(u = 0, yes = 0; u < test_num; u++) { num = rand() % 10; Mat img = (* captcha)(num); Mat vc = vec(img); if(num == cl->predict(vc)) yes++; } printf("Правильно классифицированных векторов: %u из %u (%f %%)\n", yes, test_num, yes * 100 / (double) test_num); } catch(...) { if(cl != NULL) delete cl; cl = NULL; } return cl; }
void removeOne(tp * ptr) { const unsigned size = this->size(); unsigned v; throw_null(ptr, "Невозможно удалить пустой указатель"); for(v = 0; v < size; v++) if((* this)[v] == ptr) { this->removeAt(v); break; } };
int init() { try; int ret = 0; GDALAllRegister(); OGRRegisterAll(); throw_null(drv_tiff = GDALGetDriverByName("GTiff")); throw_null(drv_r_mem = GDALGetDriverByName("MEM")); throw_null(drv_shp = OGRGetDriverByName("ESRI Shapefile")); catch; destroy(); ret = -1; finally; return ret; }
void * sfire_alloc(unsigned type_size, unsigned dim, ...) { try; void * pof, * dof, * t_dof, * ret = NULL; unsigned u, v, num, step, size, dim_1 = dim - 1, dim_2 = dim - 2, dim_size[dim]; va_list val; throw((alloc_num == BUF_SIZE)); va_start(val, dim); for(u = 0, size = 0, num = 1; u < dim; u++) { num *= (dim_size[u] = va_arg(val, unsigned)); size += (u == dim_1 ? type_size : sizeof(void *)) * num; } va_end(val); // Python'овский malloc() (malloc() через Python.h), по всей видимости, не поддерживает glibc'овский аллокатор - куча иногда переполняется throw_null((ret = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0))); alloc_pointer[alloc_num] = ret; alloc_size[alloc_num] = size; alloc_num++; for(u = 0, num = 1, dof = ret; u < dim_1; u++) { num *= dim_size[u]; pof = dof; t_dof = (dof += num * sizeof(void *)); step = (u == dim_2 ? type_size : sizeof(void *)) * dim_size[u + 1]; for(v = 0; v < num; v++, pof += sizeof(void *), t_dof += step) memcpy(pof, & t_dof, sizeof(void *)); } catch; sfire_free(ret); ret = NULL; finally; return ret; }
void CMainLoop::start(const QString src_fname, const QString src_metadata_fname, const QString dst_fname) { start(); try { struct timespec ts_before, ts_after; matrix src_frame, dst_frame; CVideoRead src(src_fname); CVideoWrite dst(dst_fname, src.fps()); display::init(25); script.init(); ctx.init(src_metadata_fname, src.frame_num(), src_fname, dst_fname, vector_map.map_fname, vector_map.height_map_fname); measure.init(); mtx.init(); vector_map.init(); while(__is_run && (src_frame = src.read()) != NULL) { ctx.next_frame(); clock_gettime(CLOCK_REALTIME, & ts_before); throw_null(dst_frame = script.run(src_frame), "Не удалось прочитать результирующий кадр"); clock_gettime(CLOCK_REALTIME, & ts_after); measure(ts_after.tv_sec - ts_before.tv_sec + (ts_after.tv_nsec - ts_before.tv_nsec) / 1000000000.0, mtx.memory()); dst.write(dst_frame); display::show_Mat(* src_frame, * dst_frame); mtx.clear(); } } catch(...) { ; } vector_map.destroy(); display::destroy(); stop(); }
void CMainLoop::image(CQtSocket & sock, CXML & packet) { try { const unsigned current_height = packet["height"].uint(), current_width = packet["width"].uint(); const unsigned buf_size = current_height * current_width; unsigned size, block_size; uint8_t * ptr; shared_ptr<uint8_t> block_buffer; ind = packet["ind"].uint(); if(height != current_height || width != current_width) { img.reset(new uint8_t[buf_size], std::default_delete<uint8_t[]>()); height = current_height; width = current_width; } throw_null(ptr = img.get()); for(size = 0; size < buf_size; ) { CXML block = sock.recv(); throw_if(block["command"].uint() != CARD_COMMAND_IMAGE_BLOCK); throw_if(block["ind"].uint() != ind); protocol::decode_base64(block["data"].value, block_buffer, block_size); memcpy(ptr + size, block_buffer.get(), block_size); size += block_size; } emit arinc_write(img.get(), height, width); } catch(...) { ; } }
CScriptEngine::CScriptEngine(CContext & ctx, CMeasure & measure, CVectorMap & vector_map) { throw_null(state = luaL_newstate(), "Не удалось инициализировать интерпретатор Lua"); luaL_openlibs(state); opencv_register(state); // Регистрация биндингов к OpenCV auxiliary_register(state); // Регистрация биндингов к дополнительному функционалу context_register(state); // Регистрация биндингов к функционалу, обрабатывающем контекст map_register(state); // Регистрация биндингов к функционалу, управляющему ВММ // ############################################################################ // Регистрация функции - обработчика доступа к модулям lua_pushlightuserdata(state, this); lua_pushlightuserdata(state, & ctx); lua_pushlightuserdata(state, & measure); lua_pushlightuserdata(state, & vector_map); lua_pushcclosure(state, run_module, 4); // TODO Отладить lua_setglobal(state, "algo"); }
CFile::CFile(const string fname) { fl = NULL; throw_null(fl = fopen(fname.c_str(), "rb")); }
int process(char * sat_dname, char * result_fname, char * shp_aoi_fname, char * shp_forest_fname, char ** svm_fname) { try; int ret = 0; unsigned v, u, t, pixel_index, height, width; uint8_t index, * fa_buf, ** sat_buf; double vec[DIM]; s_sat * sat = NULL, * fa_img = NULL; s_svm * svm[2] = { NULL, NULL }; my_printf("Begin"); // ############################################################################ // Загрузка драйверов форматов, загрузка спутникового снимка, загрузка SVM init(); throw_null((sat = sat_load(sat_dname))); for(v = 0; v < 2; v++) throw_null((svm[v] = svm_load(svm_fname[v]))); // ############################################################################ // Расчет aoi throw_null((fa_img = sat_aoi(sat, shp_aoi_fname, shp_forest_fname))); // ############################################################################ // Обработка спутникового снимка height = sat->height; width = sat->width; sat_buf = sat->pixel; fa_buf = fa_img->pixel[0]; for(v = 0; v < height; v++) { my_printf("Row %u from %u ( %lf %% )", v + 1, height, (100.0 * (v + 1)) / height); for(u = 0; u < width; u++) { pixel_index = v * width + u; if(fa_buf[pixel_index] > 0) { for(t = 0; t < DIM; t++) vec[t] = sat_buf[t][pixel_index]; if(svm_run(svm[0], vec) > 0) index = 3; else if(svm_run(svm[1], vec) > 0) index = 2; else index = 1; } else index = 0; fa_buf[pixel_index] = index; } } // ############################################################################ // Сохранение результирующего изображения throw(sat_save_ch(fa_img, result_fname, 0)); my_printf("Success"); catch; ret = -1; my_printf("Fail"); finally; for(v = 0; v < 2; v++) svm_destroy(svm[v]); sat_destroy(sat); sat_destroy(fa_img); destroy(); return ret; }
void execute(string fname) { const unsigned mem_size = 4096; int v, u, t; char next_dir, dir = 'r'; unsigned char mem[mem_size]; unsigned char * pnt = mem; Mat src; Vec3b color, next_color; memset(mem, 0, sizeof(unsigned char) * mem_size); src = imread(fname); throw_null(src.data); v = 0; u = 0; do { color = src.at<Vec3b>(v, u); if((color[0] == 0x00) && (color[1] == 0xFF) && (color[2] == 0x00)) (* pnt)++; else if((color[0] == 0x00) && (color[1] == 0x80) && (color[2] == 0x00)) (* pnt)--; else if((color[0] == 0xFF) && (color[1] == 0x00) && (color[2] == 0x00)) { pnt++; throw_if((mem + mem_size <= pnt)) } else if((color[0] == 0x80) && (color[1] == 0x00) && (color[2] == 0x00)) { pnt--; throw_if((pnt < mem)); } else if((color[0] == 0xFF) && (color[1] == 0xFF) && (color[2] == 0x00)) { if((* pnt) <= 0) { t = 0; next_color[0] = 0x80; next_color[1] = 0x80; next_color[2] = 0x00; do { throw_if(step(dir, v, u, src.size())); if(src.at<Vec3b>(v, u) == color) t++; else if(src.at<Vec3b>(v, u) == next_color) t--; } while(t >= 0); } } else if((color[0] == 0x80) && (color[1] == 0x80) && (color[2] == 0x00)) { switch(dir) { case 'r': { next_dir = 'l'; break; } case 'l': { next_dir = 'r'; break; } case 't': { next_dir = 'b'; break; } case 'b': { next_dir = 't'; break; } } t = 0; next_color[0] = 0xFF; next_color[1] = 0xFF; next_color[2] = 0x00; do { throw_if(step(next_dir, v, u, src.size())); if(src.at<Vec3b>(v, u) == color) t++; else if(src.at<Vec3b>(v, u) == next_color) t--; } while(t >= 0); step(next_dir, v, u, src.size()); } else if((color[0] == 0x00) && (color[1] == 0x00) && (color[2] == 0xFF)) printf("%c", * pnt); else if((color[0] == 0x00) && (color[1] == 0x00) && (color[2] == 0x80)) scanf("%c\n", pnt); else if((color[0] == 0x00) && (color[1] == 0xFF) && (color[2] == 0xFF)) { // Поворот против часовой стрелки switch(dir) { case 'r': { next_dir = 't'; break; } case 'l': { next_dir = 'b'; break; } case 't': { next_dir = 'l'; break; } case 'b': { next_dir = 'r'; break; } } dir = next_dir; } else if((color[0] == 0x00) && (color[1] == 0x80) && (color[2] == 0x80)) { // Поворот по часовой стрелке switch(dir) { case 'r': { next_dir = 't'; break; } case 'l': { next_dir = 't'; break; } case 't': { next_dir = 'r'; break; } case 'b': { next_dir = 'l'; break; } } dir = next_dir; } else throw_if(1); }
void translate(string fname, string prog, unsigned height, unsigned width) { unsigned v, u, t, tv, tu; Vec3b color; Mat dst(height * lwh, width * lwh, CV_8UC3); throw_null(dst.data); for(v = 0, t = 0; v < height; v++) for(u = 0; u < width; u++, t++) { switch(prog[t]) { case '+': { color[0] = 0x00; color[1] = 0xFF; color[2] = 0x00; break; } case '-': { color[0] = 0x00; color[1] = 0x80; color[2] = 0x00; break; } case '>': { color[0] = 0xFF; color[1] = 0x00; color[2] = 0x00; break; } case '<': { color[0] = 0x80; color[1] = 0x00; color[2] = 0x00; break; } case '[': { color[0] = 0xFF; color[1] = 0xFF; color[2] = 0x00; break; } case ']': { color[0] = 0x80; color[1] = 0x80; color[2] = 0x00; break; } case '.': { color[0] = 0x00; color[1] = 0x00; color[2] = 0xFF; break; } case ',': { color[0] = 0x00; color[1] = 0x00; color[2] = 0x80; break; } case '!': // Поворот против часовой стрелки { color[0] = 0x00; color[1] = 0xFF; color[2] = 0xFF; break; } case '?': // Поворот по часовой стрелке { color[0] = 0x00; color[1] = 0x80; color[2] = 0x80; break; } } for(tv = v * lwh; tv < (v + 1) * lwh; tv++) for(tu = u * lwh; tu < (u + 1) * lwh; tu++) dst.at<Vec3b>(tv, tu) = color; } imwrite(fname, dst); }
s_sat * sat_load(const char * dname) { try; bool is_first = true; unsigned v, height, width, height_width, raster_num = 0; char str[BUF_SIZE], * sstr; DIR * dir = NULL; struct dirent * entry; GDALDatasetH ds = NULL; s_sat * sat = NULL; throw_null((sat = sat_init(DIM))); throw_null((dir = opendir(dname))); while((entry = readdir(dir)) != NULL) for(v = 0; v < DIM; v++) { sprintf(str, "B%u0.tif", v + 1); sstr = strstr(entry->d_name, str); if((sstr != NULL) && (sstr[7] == '\0')) { sprintf(str, "%s/%s", dname, entry->d_name); throw_null(ds = GDALOpen(str, GA_ReadOnly)); if(is_first) { height = sat->height = GDALGetRasterYSize(ds); width = sat->width = GDALGetRasterXSize(ds); throw((GDALGetGeoTransform(ds, sat->gt_coef) == CE_Failure)); throw_null((sat->proj_ref = strdup(GDALGetProjectionRef(ds)))); height_width = height * width; is_first = false; } throw_null((sat->pixel[v] = sfire_alloc(sizeof(uint8_t), 1, height_width))); throw((GDALDatasetRasterIO(ds, GF_Read, 0, 0, width, height, sat->pixel[v], width, height, GDT_Byte, 1, NULL, 0, 0, 0) == CE_Failure)); GDALClose(ds); ds = NULL; raster_num++; break; } } throw((raster_num != DIM)); catch; sat_destroy(sat); sat = NULL; finally; if(ds != NULL) GDALClose(ds); if(dir != NULL) closedir(dir); return sat; }
s_sat * sat_aoi(s_sat * sat, const char * shp_aoi_fname, const char * shp_forest_fname) { try; OGRDataSourceH a_ds = NULL, f_ds = NULL; OGRLayerH a_layer = NULL, f_layer = NULL; OGRGeometryH a_geometry = NULL, fa_geometry = NULL, union_geometry = NULL, intersection_geometry = NULL, simplify_geometry = NULL; OGRFeatureH next_feature = NULL; s_sat * fa_img = NULL; throw_null((a_ds = OGR_Dr_Open(drv_shp, shp_aoi_fname, FALSE))); throw_null((f_ds = OGR_Dr_Open(drv_shp, shp_forest_fname, FALSE))); throw_null((a_layer = OGR_DS_GetLayer(a_ds, 0))); throw_null((f_layer = OGR_DS_GetLayer(f_ds, 0))); throw_null((a_geometry = OGR_G_CreateGeometry(wkbPolygon))); throw_null((fa_geometry = OGR_G_CreateGeometry(wkbPolygon))); OGR_L_ResetReading(a_layer); while((next_feature = OGR_L_GetNextFeature(a_layer)) != NULL) { throw_null((union_geometry = OGR_G_Union(a_geometry, OGR_F_GetGeometryRef(next_feature)))); OGR_G_DestroyGeometry(a_geometry); a_geometry = union_geometry; union_geometry = NULL; } OGR_L_SetSpatialFilter(f_layer, a_geometry); OGR_L_ResetReading(f_layer); while((next_feature = OGR_L_GetNextFeature(f_layer)) != NULL) { throw_null((intersection_geometry = OGR_G_Intersection(a_geometry, OGR_F_GetGeometryRef(next_feature)))); throw_null((union_geometry = OGR_G_Union(fa_geometry, intersection_geometry))); OGR_G_DestroyGeometry(intersection_geometry); OGR_G_DestroyGeometry(fa_geometry); fa_geometry = union_geometry; union_geometry = intersection_geometry = NULL; } throw_null((simplify_geometry = OGR_G_Simplify(fa_geometry, 0))); OGR_G_DestroyGeometry(fa_geometry); fa_geometry = simplify_geometry; simplify_geometry = NULL; throw_null((fa_img = sat_rasterize_copy(sat, fa_geometry))); catch; sat_destroy(fa_img); fa_img = NULL; finally; if(next_feature != NULL) OGR_F_Destroy(next_feature); if(a_geometry != NULL) OGR_G_DestroyGeometry(a_geometry); if(fa_geometry != NULL) OGR_G_DestroyGeometry(fa_geometry); if(union_geometry != NULL) OGR_G_DestroyGeometry(union_geometry); if(intersection_geometry != NULL) OGR_G_DestroyGeometry(intersection_geometry); if(simplify_geometry != NULL) OGR_G_DestroyGeometry(simplify_geometry); if(a_ds != NULL) OGRReleaseDataSource(a_ds); if(f_ds != NULL) OGRReleaseDataSource(f_ds); return fa_img; }
void append(tp * ptr) { throw_null(ptr, "Получен нулевой указатель"); super::append(QSharedPointer<tp>(ptr)); };