int main(int argc, char** argv) { // parse command line ---------------------------------------------- po::options_description general_opt("Allowed options are: "); general_opt.add_options() ("help,h", "display this message") ("input,i", po::value<std::string>(), "input image file name (any 2D image format accepted by DGtal::GenericReader)") ("output,o", po::value<std::string>(), "output image file name (any 2D image format accepted by DGtal::GenericWriter)") ("angle,a", po::value<double>()->default_value(0.0), "Angle in radian") ; bool parseOK=true; po::variables_map vm; try{ po::store(po::parse_command_line(argc, argv, general_opt), vm); }catch(const std::exception& ex){ trace.info()<< "Error checking program options: "<< ex.what()<< std::endl; parseOK=false; } po::notify(vm); if(vm.count("help")||argc<=1|| !parseOK) { trace.info()<< "Rotate an image by a given angle a binary object with 0 values as background points and values >0 for the foreground ones." <<std::endl << "Basic usage: "<<std::endl << "\t imgRotate [options] --input <imageName> --output <outputImage> --angle 0.3"<<std::endl << general_opt << "\n"; return 0; } //Parameters if ( ! ( vm.count ( "input" ) ) ) missingParam ( "--input" ); const std::string input = vm["input"].as<std::string>(); if ( ! ( vm.count ( "output" ) ) ) missingParam ( "--output" ); const std::string output = vm["output"].as<std::string>(); const double angle = vm["angle"].as<double>(); typedef functors::IntervalForegroundPredicate<MyImage> Binarizer; MyImage image = GenericReader<MyImage>::import( input ); trace.info() <<"Input image: "<< image<<std::endl; typedef functors::BackwardRigidTransformation2D<Z2i::Space> RotateFunctor; Z2i::RealPoint center = image.domain().upperBound(); center -= image.domain().lowerBound(); center /= 2.0; RotateFunctor rotationFunctor(center, angle, Z2i::RealPoint(0.0,0.0)); functors::Identity idD; typedef functors::DomainRigidTransformation2D<MyImage::Domain, RotateFunctor> MyDomainTransformer; MyDomainTransformer rotDomain(rotationFunctor); typedef MyDomainTransformer::Bounds Bounds; Bounds newdomain = rotDomain( image.domain()); MyImage::Domain transformedDomain ( newdomain.first, newdomain.second ); typedef ConstImageAdapter<MyImage, MyImage::Domain, RotateFunctor, MyImage::Value, functors::Identity > MyImageBackwardAdapter; MyImageBackwardAdapter backwardImageAdapter ( image, transformedDomain , rotationFunctor, idD ); backwardImageAdapter >> output; return 0; }
MyImage ReverseProcessor::preProcessImage(const MyImage& image) const { QImage *resultImage = ImageAlgorithm::reverse(image.getImage()); MyImage result(*resultImage, image.getType()); delete resultImage; return result; }
int main(int, char**){ MyImage image; //Set up parameters for the triangl vec2 v0(100, 100); vec2 v1(200, 300); vec2 v2(400, 50); float TotalArea = triangleArea(v0, v1, v2); //rasterize the triangle for (int row = 0; row < image.rows; ++row) { for (int col = 0; col < image.cols; ++col) { vec2 pt(col, row); /// Calculate the barycentric coordinates using the triangle area } } image.show(); // image.save("output.png"); ///< Does not work on Windows! return EXIT_SUCCESS; }
bool testImageCopyShort() { unsigned int nbok = 0; unsigned int nb = 0; trace.beginBlock ( "Testing smart copy of Image..." ); typedef ImageContainerBySTLVector<Z2i::Domain, int> VImage; typedef Image<VImage > MyImage; BOOST_CONCEPT_ASSERT(( CImage< MyImage > )); Z2i::Point a(0,0); Z2i::Point b(32,32); Z2i::Point c(12, 14); Z2i::Domain domain(a,b); MyImage image( new VImage(domain) ); trace.info() << "Image constructed: "<< image <<std::endl; VImage myImageC( domain ); MyImage imageFromConstRef ( myImageC ); trace.info() << "Image constructed (from constRef): "<< imageFromConstRef <<std::endl; nbok += (imageFromConstRef.getPointer().count()== 2) ? 1 : 0; nb++; trace.info() << "(" << nbok << "/" << nb << ") " << "unique" << std::endl; MyImage image3; trace.info() << "Image constructed (degulat): "<< image3 <<std::endl; trace.info() << "default: "<< image3 <<std::endl; image3 = image; nbok += (image3.getPointer().count()== 3) ? 1 : 0; nb++; trace.info() << "(" << nbok << "/" << nb << ") " << "true == true" << std::endl; trace.info() << "assignment: "<< image3 <<std::endl; nbok += (image3.getPointer().count()== 3) ? 1 : 0; nb++; trace.info() << "(" << nbok << "/" << nb << ") " << "true == true" << std::endl; image3.setValue(Z2i::Point(1,1), 4); trace.info() << "setValue on assigned: "<< image3 <<std::endl; nbok += (image3.getPointer().count()== 2) ? 1 : 0; nb++; MyImage image4(image3); trace.info() << "Image constructed (copy): "<< image4 <<std::endl; nbok += (image4.getPointer().count()== 3) ? 1 : 0; nb++; trace.info() << "(" << nbok << "/" << nb << ") " << "true == true" << std::endl; return nbok == nb; }
//callback in glut loop void display(void) { std::cout << imageToBeOutput.getWidth() << " " << imageToBeOutput.getHeight() << " " << imageToBeOutput.getChannels()<<std::endl; glClear(GL_COLOR_BUFFER_BIT); glDrawPixels(imageToBeOutput.getWidth(), imageToBeOutput.getHeight(), GL_RGBA, GL_UNSIGNED_BYTE, display_data); glFlush(); }
//keyboard handle function to implement image manipulation void handleKey(unsigned char key, int x, int y){ switch(key){ //use key 'w' or 'W' to write image case 'w': case 'W': if (writename != NULL) { Image.ImageWrite(writename); } //if the second parameter is not specified in command line, output the message 'cannot write the image' else{ std::cout << "You cannot write the image because you didn't specify a filename." << std::endl; } break; //use key 'q' or 'Q' to quit the program case 'q': // q - quit case 'Q': case 27: // esc - quit exit(0); default: // not a valid key -- just ignore it return; } }
int main(int, char**){ MyImage image; //Set up parameters for the line segment vec2 lineStart(100, 200); vec2 lineEnd(500, 220); //Line drawing - midpoint algorithm //determine if we do a x-loop or y-loop //TODO: Rasterize the line using the mid-point algorithm image.show(); // image.save("output.png"); ///< Does not work on Windows! return EXIT_SUCCESS; }
int diff_pic(unsigned char *logo_img_sample, int pyr_i, const MyImage &img_pic, int start_r, int start_c, int end_r, int end_c) { unsigned char *Ybuf_pic = img_pic.getYbuf(); int block_unit = 8; int block_len = pyr_i * BLOCK_SIZE; int error = 0; for(int i = start_r; i < end_r; i += block_unit) { for(int j = start_c; j < end_c; j += block_unit) { int min_mse = (1 << 31) - 1; for(int row = 0; row < block_len; row += block_unit) { for(int col = 0; col < block_len; col += block_unit) { int block_err = 0; for(int blc_i = 0; blc_i < block_unit; blc_i++) { for(int blc_j = 0; blc_j < block_unit; blc_j++) { int diff = logo_img_sample[(row + blc_i) * block_len + col + blc_j] - Ybuf_pic[(i + blc_i) * img_pic.getWidth() + j + blc_j]; block_err += diff * diff; } } if(block_err < min_mse) min_mse = block_err; } } error += min_mse; } } return error / (block_len / 8) / (block_len / 8); }
MyImage HistogramEqualizationProcessor::preProcessImage(const MyImage& image) const { QImage *resultImage = processImage(image.getImage()); MyImage result(*resultImage, MyImage::Gray); delete resultImage; return result; }
MyImage ToGrayProcessor::preProcessImage(const MyImage& image) const { QImage *resultImage = ImageAlgorithm::convertToGrayScale(image.getImage(), _type); MyImage result(*resultImage, MyImage::Gray); delete resultImage; return result; }
void sendDecodeSequentialMode(void* storage){ TwoByte* st = (TwoByte*) storage; int h = workingImage.getHeight(); int w = workingImage.getWidth(); Byte* imgd = workingImage.getImageData(); unsigned int q = 1<<quantizationLevel; TwoByte* tblock = new TwoByte[192]; Byte* idctblock = new Byte[192]; for(int y = 0; y < h; y+=8){ for(int x = 0; x < w; x+=8){ for(int yy= 0; yy < 8; yy++){ for(int xx = 0; xx < 8; xx++){ int src = ((y + yy)*w + (x + xx))*3; int dest = (yy*8 + xx)*3; tblock[dest] = st[src]*q; tblock[dest + 1] = st[src + 1]*q; tblock[dest + 2] = st[src + 2]*q; } } doIDCT(tblock, idctblock); for(int yy= 0; yy < 8; yy++){ for(int xx = 0; xx < 8; xx++){ int dest = ((y + yy)*w + (x + xx))*3; int src = (yy*8 + xx)*3; imgd[dest] = idctblock[src]; imgd[dest + 1] = idctblock[src + 1]; imgd[dest + 2] = idctblock[src + 2]; } } drawImage(&workingImage, nextStart); Sleep(latency); } } delete[] tblock; delete[] idctblock; MessageBox(NULL, "DECODING DONE", "Status", NULL); }
void decodeProgressiveModeSpectralSelection(TwoByte* st){ int h = workingImage.getHeight(); int w = workingImage.getWidth(); Byte* imgd = workingImage.getImageData(); unsigned int q = 1<<quantizationLevel; TwoByte* tblock = new TwoByte[192]; Byte* idctblock = new Byte[192]; memset(tblock, 0x00, sizeof(TwoByte)*192); memset(idctblock, 0x00, sizeof(Byte)*192); for(int y = 0; y < h; y+=8){ for(int x = 0; x < w; x+=8){ for(int yy= 0; yy < 8; yy++){ for(int xx = 0; xx < 8; xx++){ int src = ((y + yy)*w + (x + xx))*3; int dest = (yy*8 + xx)*3; tblock[dest] = st[src]*q; tblock[dest + 1] = st[src + 1]*q; tblock[dest + 2] = st[src + 2]*q; } } doIDCT(tblock, idctblock); for(int yy= 0; yy < 8; yy++){ for(int xx = 0; xx < 8; xx++){ int dest = ((y + yy)*w + (x + xx))*3; int src = (yy*8 + xx)*3; imgd[dest] = idctblock[src]; imgd[dest + 1] = idctblock[src + 1]; imgd[dest + 2] = idctblock[src + 2]; } } } } delete[] tblock; delete[] idctblock; drawImage(&workingImage, nextStart); }
void encode(TwoByte *store){ int h = originalImage.getHeight(); int w = originalImage.getWidth(); Byte* imgd = originalImage.getImageData(); Byte* tblock = new Byte[192]; double* dctblock = new double[192]; memset(tblock, 0x00, sizeof(Byte)*192); memset(dctblock, 0x00, sizeof(double)*192); unsigned int q = 1<<quantizationLevel; for(int y = 0; y < h; y+=8){ for(int x = 0; x < w; x+=8){ for(int yy= 0; yy < 8; yy++){ for(int xx = 0; xx < 8; xx++){ int src = ((y+yy)*w + (x + xx))*3; int dest = (yy*8 + xx)*3; tblock[dest] = imgd[src]; tblock[dest + 1] = imgd[src + 1]; tblock[dest + 2] = imgd[src + 2]; } } doDCT(tblock, dctblock); for(int yy= 0; yy < 8; yy++){ for(int xx = 0; xx < 8; xx++){ int dest = ((y+yy)*w + (x + xx))*3; int src = (yy*8 + xx)*3; store[dest] = (TwoByte)(dctblock[src]/q); store[dest + 1] = (TwoByte)(dctblock[src + 1]/q); store[dest + 2] = (TwoByte)(dctblock[src + 2]/q); } } } } delete[] tblock; delete[] dctblock; }
MyImage* MyImage::LoadImage(string path) { GLuint texture; unsigned char *data; int width, height; MyImage *image = new MyImage(); string ext; ext = path.substr( path.find_last_of('.') ); if( ext.compare("tga") == 0 ) { if( ! image->InitWithFileTGA(path) ) { delete image; return NULL; } return image; } else if( ext.compare("png") == 0 ) { // not supported delete image; return NULL; } // else formats ... texture = SOIL_load_OGL_texture(path.c_str(), SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_INVERT_Y, &data, &width, &height); if( texture == 0 ) { return NULL; } image = new MyImage( texture, data, width, height ); return image; }
int main(int argc, char** argv){ if(argc < 3){ std::cout << "usage:"<<std::endl; std::cout << "composite [foregroundImagename] [backgroundImagename]" << std::endl; std::cout << "or" <<std::endl; std::cout << "composite [foregroundImagename] [backgroundImagename] [outputIMagename]" << std::endl; exit(-1); } FileIO::getInstance().readFromFileToImage(foreImage, argv[1]); FileIO::getInstance().readFromFileToImage(backImage, argv[2]); imageToBeOutput = foreImage.over(backImage,0,0); display_data = new GLubyte[imageToBeOutput.getWidth()*imageToBeOutput.getHeight()*4]; imageToBeOutput.displayOutput(display_data); if(argc>3){ FileIO::getInstance().writeImageToFile(imageToBeOutput,argv[3]); } glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE|GLUT_RGBA); glutInitWindowSize(imageToBeOutput.getWidth(), imageToBeOutput.getHeight()); glutInitWindowPosition(0, 0); glutCreateWindow(argv[0]); init(); glutDisplayFunc(display); glutMainLoop(); return 0; }
void sendSuccessiveBits(void* storage){ TwoByte* st = (TwoByte*) storage; int h = workingImage.getHeight(); int w = workingImage.getWidth(); int len = h*w*3; TwoByte *newst = new TwoByte[len]; memset(newst, 0x00, sizeof(TwoByte)*len); TwoByte offset = 1<<12; for(int k = 12; k >= 0; --k){ for(int i = 0; i < len; ++i){ TwoByte temp = st[i] + offset; temp &= (1<<k); newst[i] |= temp; } decodeProgressiveModeBitApproximation(newst, offset); Sleep(latency); } delete[] newst; MessageBox(NULL, "DECODING DONE", "Status", NULL); }
MyImage MyImage::over(MyImage& image, int posx, int posy){ MyImage newImage(image.to4ChannelsImage()); for(int y = 0; y< height && (y+posy)< newImage.height ; y++){ for(int x = 0; x< width && (x+posx< newImage.width ); x++){ for(int c = 0; c< 3; c++){ newImage.data[c + (x+posx) *4 + (y+posy)*newImage.width*4]= newImage.data[c + (x+posx) *4 + (y+posy)*newImage.width*4] * (255-data[3+x*4+y*width*4])/255+data[c+ x*4 + y*width*4]*(data[3+x*4+y*width*4])/255; } } } return newImage; }
bool compareImage_basic(const MyImage &img_logo, const MyImage &img_pic) { int *his_logo = getHistogram_H(img_logo, 0, 0, img_logo.getHeight(), img_logo.getWidth()); int *his_pic = getHistogram_H(img_pic, 0, 0, img_pic.getHeight(), img_pic.getWidth()); print_arr(his_logo, H_N); print_arr(his_pic, H_N); int total_pixel = img_logo.getWidth() * img_logo.getHeight(); retainMajority(his_logo, 0.9, H_N); TRACE("After retaining majority\n"); print_arr(his_logo, H_N); filter(his_logo, his_pic, H_N); TRACE("After filtering\n"); print_arr(his_pic, H_N); double *norm_his_logo = normalize(his_logo, H_N); double *norm_his_pic = normalize(his_pic, H_N); double diff = differ(norm_his_logo, norm_his_pic, H_N); TRACE("ecu diff: %lf\n", diff); delete his_logo; delete his_pic; delete norm_his_logo; delete norm_his_pic; return diff <= THRESHOLD; }
ToBlackAndWhiteDialog::ToBlackAndWhiteDialog(const MyImage& image, const Area& area, QWidget *parent) : QDialog(parent), ui(new Ui::ToBlackAndWhiteDialog), _area(area) { ui->setupUi(this); _image = image.getImage(); changing = false; single = true; black = true; singleThreshold = 0; thresholdItem = new ThresholdItem(); plot = new BasicStatisticPlot( ImageAlgorithm::getStatistic(image.getImage(), ImageAlgorithm::Green)); ui->widget_2->layout()->addWidget(plot); plot->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Maximum); thresholdItem->attach(plot); QVector<int> thresholds; thresholds.push_back(0); thresholdItem->setThresholds(thresholds); connect(thresholdItem, SIGNAL(thresholdChanged(QVector<int>)), this, SLOT(multipleChanged(QVector<int>))); xPlotPicker = new XPlotPicker(QwtPlot::xBottom, QwtPlot::yLeft, QwtPlotPicker::VLineRubberBand, QwtPicker::AlwaysOn, plot->canvas()); xPlotPicker->setRubberBandPen(QColor(0, 0, 255, 160)); xPlotPicker->setTrackerPen(QColor(0, 0, 255, 160)); xPlotPicker->setEnabled(true); connect(xPlotPicker, SIGNAL(pressAt(int)), this, SLOT(singleChanged(int))); connect(ui->thresholdSpinBox, SIGNAL(valueChanged(int)), this, SLOT(singleChanged(int))); marker = new QwtPlotMarker(); marker->setValue(0.0, 0.0); marker->setLineStyle(QwtPlotMarker::VLine); marker->setLabelAlignment(Qt::AlignRight | Qt::AlignBottom); marker->setLinePen(QPen(Qt::green, 0, Qt::DashDotLine)); marker->attach(plot); connect(ui->thresholdsEdit, SIGNAL(textEdited(QString)), this, SLOT(multipleTextChanged(QString))); connect(ui->blackButton, SIGNAL(toggled(bool)), this, SLOT(startWithBlack(bool))); connect(ui->whiteButton, SIGNAL(toggled(bool)), this, SLOT(startWithWhite(bool))); resetPreview(); }
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // TODO: Place code here. MSG msg; HACCEL hAccelTable; int w, h; int quant = 0, coEff = 0; if(SQUARE == 1) { w = WIDTH; h = HEIGHT; } else if(RECTANGULAR == 1) { w = WIDTH; h = HEIGHT; } char ImagePath[_MAX_PATH]; sscanf(lpCmdLine, "%s %d %d", &ImagePath, &quant, &coEff); if(SQUARE == 1) { w = 512; h = 512; } else if(RECTANGULAR == 1) { w = 352; h = 288; } myImage.setWidth(w); myImage.setHeight(h); myImage.setQuant(quant); myImage.setCoEff(coEff); myImage.setImagePath(ImagePath); myImage.FillInputRGBSpace(); myImage.GrayScale2YUV(); if(DCT_ACTIVE == 1) myImage.DCTBasedCompDecomp(); if(IDCT_ACTIVE == 1) { remove("zigzag.txt"); myImage.IDCTBasedCompDecomp(); } myImage.YUV2RGB(); if(TESTZIGZAG == 1) { remove("test.txt"); myImage.TestZigTheZag(); } // Initialize global strings LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_IMAGE, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // Perform application initialization: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_IMAGE); // Main message loop: while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return msg.wParam; }
// // FUNCTION: WndProc(HWND, unsigned, WORD, LONG) // // PURPOSE: Processes messages for the main window. // // WM_COMMAND - process the application menu // WM_PAINT - Paint the main window // WM_DESTROY - post a quit message and return // // LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; TCHAR szHello[MAX_LOADSTRING]; LoadString(hInst, IDS_HELLO, szHello, MAX_LOADSTRING); switch (message) { case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // Parse the menu selections: switch (wmId) { case IDM_ABOUT: DialogBox(hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, (DLGPROC)About); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_PAINT: { hdc = BeginPaint(hWnd, &ps); // TODO: Add any drawing code here... RECT rt; GetClientRect(hWnd, &rt); // Top Text char text[1000]; // Image Header setup BITMAPINFO bmi; CBitmap bitmap; memset(&bmi,0,sizeof(bmi)); bmi.bmiHeader.biSize = sizeof(bmi.bmiHeader); bmi.bmiHeader.biWidth = myImage.getWidth(); bmi.bmiHeader.biHeight = -myImage.getHeight(); // Use negative height. DIB is top-down. bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biBitCount = 24; bmi.bmiHeader.biCompression = BI_RGB; bmi.bmiHeader.biSizeImage = myImage.getWidth()*myImage.getHeight(); // Draw Processed image sprintf(text, "\n %s -> display", myImage.getImagePath()); DrawText(hdc, text, strlen(text), &rt, DT_LEFT); sprintf(text, "\n %s -> Gray Scaled -> YUV -> DCT -> Quant [ %d ] -> Dequant [ %d ] -> IDCT [ %d Co-Efficient(s) ] ", myImage.getImagePath(), myImage.getQuant(), myImage.getQuant(), myImage.getCoEff()); DrawText(hdc, text, strlen(text), &rt, DT_RIGHT); // Draw image SetDIBitsToDevice(hdc, 100,100,myImage.getWidth(),myImage.getHeight(), 0,0,0,myImage.getHeight(), myImage.getBytesRGBSTART(),&bmi,DIB_RGB_COLORS); SetDIBitsToDevice(hdc, 300+myImage.getWidth()+50,100,myImage.getWidth(),myImage.getHeight(), 0,0,0,myImage.getHeight(), myImage.getBytesRGBEND(),&bmi,DIB_RGB_COLORS); EndPaint(hWnd, &ps); } break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; }
/** @function main */ int main( int argc, char** argv ) { //300 350 double probability = 0.6; std::vector<string> sourceVector = saveFileName(argv[1]); std::vector<string> searchVector = saveFileName(argv[2]); double matched = 0; for(std::vector<string>::iterator sourceIterator = sourceVector.begin(); sourceIterator != sourceVector.end(); sourceIterator++ ){ for(std::vector<string>::iterator searchIterator = searchVector.begin(); searchIterator != searchVector.end(); searchIterator++ ){ if (*sourceIterator == *searchIterator) { matched++; break; } } } probability *= (matched / sourceVector.size()); MyImage *image = new MyImage(); image->setWidth(352); image->setHeight(288); image->setImagePath(argv[1]); if(!image->ReadImage()){ std::cout << "Error reading MyImage" << std::endl; } printf("%s", argv[1]); FILE *f = fopen(argv[1], "rb"); if (!f) { printf("error\n"); exit(1); } unsigned char pixels[352 * 288 * 3]; fread(pixels, sizeof(unsigned char), 352*288 * 3, f); fclose(f); cv::Mat object(Size(352, 288), CV_8UC3, pixels); namedWindow("image", CV_WINDOW_AUTOSIZE); imshow("image", object); if( !object.data ) { std::cout<< "Error reading object " << std::endl; return -1; } cv::Mat tmp, alpha; threshold(object, object, 255, 0, THRESH_TOZERO_INV); cv::Rect myROI(100, 100, 150, 150); int minHessian = 1000; cv::SurfFeatureDetector detector( minHessian ); std::vector<cv::KeyPoint> kp_object; detector.upright = false; detector.detect( object, kp_object ); cv::SurfDescriptorExtractor extractor; cv::Mat des_object; extractor.compute( object, kp_object, des_object ); cv::FlannBasedMatcher matcher; cv::namedWindow("Good Matches"); std::vector<cv::Point2f> obj_corners(4); //Get the corners from the object obj_corners[0] = cvPoint(0,0); obj_corners[1] = cvPoint( object.cols, 0 ); obj_corners[2] = cvPoint( object.cols, object.rows ); obj_corners[3] = cvPoint( 0, object.rows ); char key = 'a'; int framecount = 0; while (key != 27) { if (framecount < 5) { framecount++; continue; } cv::Mat des_image, img_matches; std::vector<cv::KeyPoint> kp_image; std::vector<std::vector<cv::DMatch > > matches; std::vector<cv::DMatch > good_matches; std::vector<cv::Point2f> obj; std::vector<cv::Point2f> scene; std::vector<cv::Point2f> scene_corners(4); cv::Mat H; MyImage *sceneMyPic = new MyImage(); sceneMyPic->setWidth(352); sceneMyPic->setHeight(288); sceneMyPic->setImagePath(argv[2]); sceneMyPic->ReadImage(); cv::Mat image(Size(352, 288), CV_8UC3, sceneMyPic->getImageData()); detector.detect( image, kp_image ); extractor.compute( image, kp_image, des_image ); matcher.knnMatch(des_object, des_image, matches, 2); for(int i = 0; i < cv::min(des_image.rows-1,(int) matches.size()); i++) //THIS LOOP IS SENSITIVE TO SEGFAULTS { if((matches[i][0].distance < 0.8*(matches[i][1].distance)) && ((int) matches[i].size()<=2 && (int) matches[i].size()>0)) { good_matches.push_back(matches[i][0]); } } drawMatches( object, kp_object, image, kp_image, good_matches, img_matches, cv::Scalar::all(-1), cv::Scalar::all(-1), std::vector<char>(), cv::DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS ); if (good_matches.size() >= 4) { Point2f averagePoint; for( int i = 0; i < good_matches.size(); i++ ) { obj.push_back( kp_object[ good_matches[i].queryIdx ].pt ); scene.push_back( kp_image[ good_matches[i].trainIdx ].pt ); averagePoint.x += kp_image[ good_matches[i].trainIdx ].pt.x; averagePoint.y += kp_image[ good_matches[i].trainIdx ].pt.y; } averagePoint.x /= good_matches.size(); averagePoint.y /= good_matches.size(); int inRange = 0; int delta = 60; for( int i = 0; i < good_matches.size(); i++ ){ int x =kp_image[ good_matches[i].trainIdx ].pt.x; int y =kp_image[ good_matches[i].trainIdx ].pt.y; if ((x > (averagePoint.x - delta) && x < (averagePoint.x + delta)) && (y > (averagePoint.y - delta) && (y < (averagePoint.y + delta)))) { inRange++; } } if (probability + (double)inRange / good_matches.size() > 0.8) { printf("found\n"); }else{ MyImage *objectPic = new MyImage(); objectPic->setWidth(352); objectPic->setHeight(288); objectPic->setImagePath(argv[1]); objectPic->ReadImage(); cv::Mat objectImage(Size(352, 288), CV_8UC3, objectPic->getImageData()); cv::Mat smallerQueryImage; resize(objectImage, smallerQueryImage, Size(16, 16), 0,0, INTER_CUBIC); cvtColor(objectImage, objectImage, COLOR_RGB2HSV); for (int x = 0; x < 352; x += 16) { for (int y = 0; y < 288; y += 16) { Rect region(Point(x, y), Size(16, 16)); cv::Mat subSampleOfScene = image(region); cvtColor(subSampleOfScene, subSampleOfScene, COLOR_RGB2HSV); int h_bins = 50; int s_bins = 60; int histSize[] = { h_bins, s_bins }; float h_ranges[] = { 0, 180 }; float s_ranges[] = { 0, 256 }; const float* ranges[] = { h_ranges, s_ranges }; int channels[] = { 0, 1 }; MatND hist_base; MatND hist_test; calcHist( &smallerQueryImage, 1, channels, Mat(), hist_base, 2, histSize, ranges, true, false ); normalize( hist_base, hist_base, 0, 1, NORM_MINMAX, -1, Mat() ); calcHist( &subSampleOfScene, 1, channels, Mat(), hist_test, 2, histSize, ranges, true, false ); normalize( hist_test, hist_test, 0, 1, NORM_MINMAX, -1, Mat() ); double base_test1 = compareHist(hist_base, hist_test, CV_COMP_CORREL); if (base_test1 > 0.1) { probability += base_test1; } } } if (probability > 0.8) { printf("found with confidence: %f\n", probability); } else{ printf("not found\n"); } } line(img_matches, cv::Point2f(averagePoint.x - 40 + sceneMyPic->getWidth(), averagePoint.y - 40), cv::Point2f(averagePoint.x + 40 + sceneMyPic->getWidth(), averagePoint.y - 40), cv::Scalar(0, 255, 0), 4); line(img_matches, cv::Point2f(averagePoint.x + 40 + sceneMyPic->getWidth(), averagePoint.y - 40), cv::Point2f(averagePoint.x + 40 + sceneMyPic->getWidth(), averagePoint.y + 40), cv::Scalar(0, 255, 0), 4); line(img_matches, cv::Point2f(averagePoint.x + 40 + sceneMyPic->getWidth(), averagePoint.y + 40), cv::Point2f(averagePoint.x - 40 + sceneMyPic->getWidth(), averagePoint.y + 40), cv::Scalar(0, 255, 0), 4); line(img_matches, cv::Point2f(averagePoint.x - 40 + sceneMyPic->getWidth(), averagePoint.y + 40), cv::Point2f(averagePoint.x - 40 + sceneMyPic->getWidth(), averagePoint.y - 40), cv::Scalar(0, 255, 0), 4); } imshow("Good matches", img_matches); key = cv::waitKey(0); } return 0; }
int main() { HandGesture hg; myImage.InitKinect(); init(&myImage); while (1) { myImage.Update(); if (!myImage.src.empty()) break; } char c; //建立窗口 namedWindow("camera", 1);//显示视频原图像的窗口 //捕捉鼠标 setMouseCallback("camera", onMouse, 0); while (1) { myImage.Update(); //画出矩形框 rectangle(myImage.src, Select, Scalar(255, 0, 0), 3, 8, 0);//能够实时显示在画矩形窗口时的痕迹 //显示视频图片到窗口 imshow("camera", myImage.src); cout << Select.x << " " << Select.y << endl; cout << Select.width << " " << Select.height << endl; // select.zeros(); //键盘响应 c = (char)waitKey(20); if (27 == c)//ESC键 break; } destroyWindow("camera"); myImage.Update(Select); for (int i = 0; i < NSAMPLES; ++i) { avgColor[i][0] = 13; avgColor[i][1] = 90; avgColor[i][2] = 130; } initWindows(); initTrackbars(); while (1) { hg.frameNumber++; myImage.Update(Select); rectangle(myImage.temp, Select, Scalar(255, 0, 0), 3, 8, 0);//能够实时显示在画矩形窗口时的痕迹 pyrDown(myImage.src, myImage.srcLR); blur(myImage.srcLR, myImage.srcLR, Size(3, 3)); cvtColor(myImage.srcLR, myImage.srcLR, ORIGCOL2COL); produceBinaries(&myImage); cvtColor(myImage.srcLR, myImage.srcLR, COL2ORIGCOL); makeContours(&myImage, &hg, Select); hg.getFingerNumber(&myImage); showWindows(myImage); if (cv::waitKey(30) == char('q')) break; } destroyAllWindows(); return 0; }
bool compareImage_v2(MyImage &img_logo, MyImage &img_pic) { int row_n = img_pic.getHeight() / BLOCK_SIZE; int col_n = img_pic.getWidth() / BLOCK_SIZE; int *his_logo = getHistogram(img_logo, 0, 0, img_logo.getHeight(), img_logo.getWidth()); //int *his_logo = getHistogram_H(img_logo, 0, 0, img_logo.getHeight(), img_logo.getWidth()); //int *his_pic = getHistogram_H(img_pic, 0, 0, img_pic.getHeight(), img_pic.getWidth()); //print_arr(his_logo, histo_size); //print_arr(his_logo, histo_size_h); //delete his_pic; double *norm_logo = normalize(his_logo, histo_size); //double *norm_logo = normalize(his_logo, histo_size_h); //print_arr_d(norm_logo, histo_size); //print_arr_d(norm_logo, histo_size_h); int **block_histos = new int*[row_n * col_n]; int total_blc = 0; for(int i = 0; i < img_pic.getHeight(); i += BLOCK_SIZE) { for(int j = 0; j < img_pic.getWidth(); j += BLOCK_SIZE) { //TRACE("i: %d, j: %d\n", i, j); block_histos[total_blc++] = getHistogram(img_pic, i, j, i + BLOCK_SIZE, j + BLOCK_SIZE); // print_arr(block_histos[total_blc - 1], H_N); } } int window_size = min(row_n, col_n); //double min_diff = 1000.0; //int min_x = -1, min_y = -1, min_size = -1; std::priority_queue<Box, std::vector<Box>, CompareBox> best_boxes; int max_heap_size = 5; while(window_size > 0) { for(int row = 0; row <= row_n - window_size; row++) { for(int col = 0; col <= col_n - window_size; col++) { int *local_histo = new int[histo_size]; //int *local_histo = new int[histo_size_h]; for(int x = 0; x < histo_size; x++) local_histo[x] = 0; //for(int x = 0; x < histo_size_h; x++) local_histo[x] = 0; for(int x = row; x < row + window_size; x++) { for(int y = col; y < col + window_size; y++) { int block_index = x * col_n + y; for(int z = 0; z < histo_size; z++) //for(int z = 0; z < histo_size_h; z++) local_histo[z] += block_histos[block_index][z]; } } double *norm_local = normalize(local_histo, histo_size); //double *norm_local = normalize(local_histo, histo_size_h); //print_arr_d(norm_local, H_N); //print_arr_d(norm_logo, H_N); double diff = differ(norm_local, norm_logo, histo_size); //double diff = differ(norm_local, norm_logo, histo_size_h); //TRACE("row: %d, col: %d, size: %d, diff: %lf\n", row, col, window_size, diff); /* if(row == 3 && col == 6 && window_size == 2) { print_arr_d(norm_local, histo_size); TRACE("diff: %lf\n", diff); } */ if(best_boxes.size() == max_heap_size && best_boxes.top().diff > diff) { delete best_boxes.top().histogram; best_boxes.pop(); } if(best_boxes.size() < max_heap_size) { Box new_box = {row, col, window_size, diff, local_histo}; //TRACE("r: %d, c: %d, size: %d, diff: %lf\n", new_box.row, new_box.col, new_box.len, new_box.diff); best_boxes.push(new_box); } else delete local_histo; delete norm_local; } } window_size--; } //TRACE("row: %d, col: %d, size: %d, diff: %lf\n", min_y, min_x, min_size, min_diff); //int length = min_size * BLOCK_SIZE; img_pic.RGBtoGray(); img_logo.RGBtoGray(); unsigned char **pyramid = create_img_pyr(img_logo, 0); int min_err = (1 << 31) - 1; double min_diff = 10.0; //printf("here\n"); while(!best_boxes.empty()) { Box best_box = best_boxes.top(); TRACE("row: %d, col: %d, size: %d, diff: %lf\n", best_box.row, best_box.col, best_box.len, best_box.diff); //printf("row: %d, col: %d, size: %d, diff: %lf\n", best_box.row, best_box.col, best_box.len, best_box.diff); //print_arr(best_box.histogram, histo_size); //print_arr(best_box.histogram, histo_size_h); img_pic.DrawBox(best_box.row * BLOCK_SIZE, best_box.col * BLOCK_SIZE, (best_box.row + best_box.len)* BLOCK_SIZE, (best_box.col + best_box.len) * BLOCK_SIZE); best_boxes.pop(); if(best_boxes.empty()) min_err = diff_pic(pyramid[best_box.len - 1], best_box.len, img_pic, best_box.row * BLOCK_SIZE, best_box.col * BLOCK_SIZE, (best_box.row + best_box.len)* BLOCK_SIZE, (best_box.col + best_box.len) * BLOCK_SIZE); //TRACE("cur_err: %d\n", cur_err); //printf("cur_err: %d\n", cur_err); //if(cur_err < min_err) min_err = cur_err; if(best_box.diff < min_diff) min_diff = best_box.diff; delete best_box.histogram; } TRACE("min_square_error: %d\n", min_err); TRACE("min_diff: %f\n", min_diff); delete his_logo; delete norm_logo; //delete [] block_histos; for(int i = 0; i < total_blc; i++) { delete block_histos[i]; } for(int i = 0; i < 9; i++) { delete pyramid[i]; } delete pyramid; delete block_histos; if(min_diff <= 0.02) return true; if(min_diff >= 0.33) return false; return min_err < 400000; }
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // TODO: Place code here. MSG msg; HACCEL hAccelTable; //prepare cos value table cosVal[0] = 1; cosVal[1] = cos(PI/16); cosVal[2] = cos(PI/8); cosVal[3] = cos((3*PI)/16); cosVal[4] = c; cosVal[5] = cos((5*PI)/16); cosVal[6] = cos((3*PI)/8); cosVal[7] = cos((7*PI)/16); cosVal[8] = 0; cosVal[9] = -sin(PI/16); cosVal[10] = -sin(PI/8); cosVal[11] = -sin((3*PI)/16); cosVal[12] = -c; cosVal[13] = -sin((5*PI)/16); cosVal[14] = -sin((3*PI)/8); cosVal[15] = -sin((7*PI)/16); for(int i = 0; i < 16; ++i){ cosVal[i+16] = - cosVal[i]; } int wd, ht; char ImagePath[_MAX_PATH]; sscanf(lpCmdLine, "%s %d %d %d", &ImagePath, &quantizationLevel, &deliveryMode, &latency); if(quantizationLevel > 7 || quantizationLevel < 0){ MessageBox(NULL, "Quantization Level can be 0 to 7 only.", NULL, NULL); return FALSE; } if(deliveryMode > 3 || deliveryMode < 1){ MessageBox(NULL, "Delivery Mode can be either 1 2 or 3 only.", NULL, NULL); return FALSE; } if(latency < 0){ MessageBox(NULL, "Latency can be greater than 0 only.", NULL, NULL); return FALSE; } wd=352; ht=288; originalImage.setWidth(wd); originalImage.setHeight(ht); originalImage.setImagePath(ImagePath); originalImage.ReadImage(); nextStart = wd + 50; workingImage.setHeight(ht); workingImage.setWidth(wd); Byte* imgd = new Byte[ht*wd*3]; memset(imgd, 0xFF, sizeof(Byte)*ht*wd*3); workingImage.setImageData(imgd); imgd = NULL; // Initialize global strings LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_IMAGE, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // Perform application initialization: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } TwoByte *s = new TwoByte[ht*wd*3]; MyStorage strg; strg.setStorage(s); encode(s); if(deliveryMode == 1){ _beginthread (sendDecodeSequentialMode, 0, s); } else if(deliveryMode == 2){ _beginthread (sendSpectralSelection, 0, s); } else if(deliveryMode == 3){ _beginthread (sendSuccessiveBits, 0, s); } hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_IMAGE); // Main message loop: while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return msg.wParam; }
void mask() { if ((pvtag == 0)&&(sstag == 1)) { unsigned char *hsv, *ss; hsv = Image.Threshold(tl,th,thv,ths); Image.SetData(hsv); ss = Image.SS(ks); Image.SetData(ss); } if ((pvtag == 1)&&(sstag == 0)) { unsigned char *pv; pv = Image.PV(k); Image.SetData(pv); } if ((pvtag == 0)&&(sstag == 0)) { unsigned char *hsv; hsv = Image.Threshold(tl,th,thv,ths); Image.SetData(hsv); } if ((pvtag == 1)&&(sstag == 1)) { unsigned char *pv, *ss; pv = Image.PV(k); Image.SetData(pv); ss = Image.SS(ks); Image.SetData(ss); } // glutPostRedisplay(); }
void RenderScene(){ Image.ImageDisplay(); }
int main(int argc, char** argv) { //if neither one or two parameters are input in command line, output the instruction of the usage of the program std::cout<<"argc"<<argc<<std::endl; if (argc < 2 || argc > 5) { std::cerr << "Usage: " << argv[0] << " [filename][writename][option] " << std::endl; exit(1); } //if second parameter is specified, store the file name to write the image else if (argc == 3) { std::string arg = argv[2]; if (arg == "-pv"){ pvtag = 1; std::cout << "pvtag set." << std::endl; } else if (arg == "-ss"){ sstag = 1; std::cout << "sstag set." << std::endl;} else { writename = argv[2]; std::cout << "writename is " << writename << std::endl; } } else if (argc == 4) { std::string arg = argv[3]; std::string arg2 = argv[2]; if (arg == "-pv" && arg2 != "-ss") { pvtag = 1; writename = argv[2]; std::cout << "writename is " << writename << std::endl; std::cout << "pvtag is set." << std::endl; } else if (arg == "-ss" && arg2 != "-pv") { sstag = 1; writename = argv[2]; std::cout << "writename is " << writename << std::endl; std::cout << "sstag is set." << std::endl; } else if ((arg == "-ss" && arg2 == "-pv") || (arg == "-pv" && arg2 == "-ss")) { sstag = 1; pvtag = 1; std::cout << "sstag is set." << std::endl; std::cout << "pvtag is set." << std::endl; } else { std::cerr << "Usage: " << argv[0] << " [filename][writename][option] " << std::endl; exit(1); } } else //argc == 5 { std::string arg1 = argv[3], arg2 = argv[4]; if (((arg1 == "-pv") && (arg2 == "-ss"))||((arg1 == "-ss") && (arg2 == "-pv"))) { pvtag = 1; sstag = 1; writename = argv[2]; std::cout << "writename is " << writename << std::endl; std::cout << "sstag and pvtag are set." << std::endl; } } //get the filename of the image, set the filename and read the image to get basic information of it filename = argv[1]; std::cout << filename << std::endl; Image.SetFilename(filename); Image.ImageRead(); Image.SetOriginalData(); int h = Image.GetHeight(); int w = Image.GetWidth(); int c = Image.GetChannel(); mask(); //start up the glut utilities glutInit(&argc, argv); //create the graphics window, giving width, height and title text glutInitDisplayMode(GLUT_SINGLE | GLUT_DEPTH | GLUT_RGBA); glutInitWindowSize((Image.GetWidth()),Image.GetHeight()); glutCreateWindow("Image"); //glut keyboard function, display function and mouse function glutKeyboardFunc(handleKey); glutDisplayFunc(RenderScene); glutSpecialFunc(kfunc); //use glblend to display the alpha range 0~255 only in this program glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); glBlendEquation(GL_FUNC_ADD); //define the drawing coordinate system on the viewport glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0, w, 0, h); // specify window clear (background) color to be opaque white glClearColor(1, 1, 1, 1); //glut loops glutMainLoop(); return 0; }
void sendSpectralSelection(void* storage){ TwoByte* st = (TwoByte*) storage; int h = workingImage.getHeight(); int w = workingImage.getWidth(); int len = h*w*3; TwoByte *newst = new TwoByte[len]; memset(newst, 0x00, sizeof(TwoByte)*len); int xx, yy; int t = 0; for(int k= 0; k <= 14; ++k){ if((k%7)%2 == 0){ if(k == 7 || k==14){ xx = 7; yy = k-7; } else{ yy = k%7; xx = k-yy; } } else{ xx = k%7; yy = k-xx; } if(yy > xx){ t = yy - xx; for(int i = 0; i <= t; ++i){ for(int y = 0; y < h; y+=8){ for(int x = 0; x < w; x+=8){ int index = ((y + yy)*w + (x + xx))*3; newst[index] = st[index]; newst[index + 1] = st[index + 1]; newst[index + 2] = st[index + 2]; } } decodeProgressiveModeSpectralSelection(newst); Sleep(latency); yy--;xx++; } } else{ t = xx - yy; for(int i = 0; i <= t; ++i){ for(int y = 0; y < h; y+=8){ for(int x = 0; x < w; x+=8){ int index = ((y + yy)*w + (x + xx))*3; newst[index] = st[index]; newst[index + 1] = st[index + 1]; newst[index + 2] = st[index + 2]; } } decodeProgressiveModeSpectralSelection(newst); Sleep(latency); yy++;xx--; } } } delete[] newst; MessageBox(NULL, "DECODING DONE", "Status", NULL); }