int main() { int i, j; int result = 0; result = sobel(); for (i = 0; i < 1; i++) { loop1: for (j = 0; j < 1; j++) { // for(i=0; i<ROWS; i++) { // loop1: for(j=0; j<COLS; j++){ if (outdata[i][j] != elaine_512_golden_output[i][j]) { result++; // printf("%d %d %d %d\n", i, j, // elaine_512_golden_output[i][j], // outdata[i][j]); } } } if (!result) printf("PASS!\n"); else printf("FAIL with %d differences\n", result); return 0; }
static gint edge_detect (const guchar *data) { gint ret; switch (evals.edgemode) { case SOBEL: ret = sobel (data); break; case PREWITT: ret = prewitt (data); break; case GRADIENT: ret = gradient (data); break; case ROBERTS: ret = roberts (data); break; case DIFFERENTIAL: ret = differential (data); break; case LAPLACE: ret = laplace (data); break; default: ret = -1; break; } return CLAMP0255 (ret); }
int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); Q_UNUSED(a) QImage inImage("lena.png"); inImage = inImage.convertToFormat(QImage::Format_Grayscale8); QImage outImage(inImage.size(), inImage.format()); QVector<int> gradient; QVector<int> direction; sobel(inImage, gradient, direction); QVector<int> thinned = thinning(inImage.width(), inImage.height(), gradient, direction); QVector<int> thresholded = threshold(75, 150, thinned); QVector<int> canny = hysteresis(inImage.width(), inImage.height(), thresholded); const int *iImg = canny.constData(); quint8 *oImg = outImage.bits(); int size = inImage.width() * inImage.height(); for (int i = 0; i < size; i++) oImg[i] = qBound(0, iImg[i], 255); outImage.save("canny.png"); return EXIT_SUCCESS; }
int main() { //---------- start nm program ------------ int fromHost=ncl_hostSync(0xC0DE6406); // send handshake to host if (fromHost!=0xC0DE0086){ // get handshake from host return -1; } // Get image parameters from host int width = ncl_hostSync(0); int height= ncl_hostSync(1); int size = width*height; // Check memory allocation if (src ==0 || dst==0){ ncl_hostSync(0xDEADB00F); // send error to host return -1; } else ncl_hostSync(0x600DB00F); // send ok to host ncl_hostSync((int)src); // Send source buffer address to host ncl_hostSync((int)dst); // Send result buffer address to host ncl_hostSync(0); // Wait source buffer is ready clock_t t0=clock(); sobel((unsigned char*)src,(unsigned char*)dst, width, height); clock_t t1=clock(); ncl_hostSync(t1-t0); // Send elapsed time return 1; }
int main(int argc, char* argv[]) { double PSNR; PSNR = sobel(input, output, golden); printf("PSNR of original Sobel and computed Sobel image: %g\n", PSNR); printf("A visualization of the sobel filter can be found at " OUTPUT_FILE ", or you can run 'make image' to get the jpg\n"); return 0; }
static void sobel_preview_update (GimpPreview *preview) { sobel (gimp_drawable_preview_get_drawable (GIMP_DRAWABLE_PREVIEW (preview)), bvals.horizontal, bvals.vertical, bvals.keep_sign, preview); }
//Main function int main(int argc, char* argv[]) { if (argc != 2) { std::cout << "Usage: colorcanny image" << std::endl; return(0); } //CImg for output cimg_library::CImg <unsigned char> image(argv[1]); cimg_library::CImg <unsigned char> image_copy(image.width(), image.height(), image.depth(), image.spectrum()); cimg_library::CImg <unsigned char> image_qwaf(image.width(), image.height(), image.depth(), image.spectrum()); cimg_library::CImg <unsigned char> sobel(image.width(), image.height(), image.depth(), image.spectrum()); cimg_library::CImg <unsigned char> sobel_dir(image.width(), image.height(), image.depth(), image.spectrum()); cimg_library::CImg <unsigned char> nms_image(image.width(), image.height(), image.depth(), image.spectrum()); cimg_library::CImg <unsigned char> nms_image_dir(image.width(), image.height(), image.depth(), image.spectrum()); //Do a copy for testing for (int x=0; x<image.width(); x++) { for (int y=0; y<image.height(); y++) { unsigned char col[] = {image(x,y,0,0), image(x,y,0,1), image(x,y,0,2)}; image_copy.draw_point(x,y,col); } } applyQWAF(image, image_qwaf); image_qwaf.save("image_qwaf.bmp"); //Copy to see if everything is working properly image_copy.save("image_copy.bmp"); //Apply a gaussian blur image.blur(1.6); //Vectors std::vector<unsigned char> magnitude; std::vector<unsigned char> nms; std::vector<float> direction; //Apply the sobel operator to the image and then non-maximum supression sobelOperator(image, magnitude, direction); NMS(nms, magnitude, direction, image.width(), image.height()); //Write the magnitude and direction out to images writeMagnitude(sobel, magnitude); writeMagnitudeDirection(sobel_dir, magnitude, direction); writeMagnitude(nms_image, nms); writeMagnitudeDirection(nms_image_dir, nms, direction); //Write the images out to files sobel.save("sobel.bmp"); sobel_dir.save("sobel_direction.bmp"); nms_image.save("non_maxima.bmp"); nms_image_dir.save("non_maxima_dir.bmp"); //Return successful return 0; }
int main() { //---------- start nm program ------------ int fromHost=ncl_hostSync(0xC0DE6406); // send handshake to host if (fromHost!=0xC0DE0086){ // get handshake from host return -1; } // Get image parameters from host int width = ncl_hostSync(0); int height= ncl_hostSync(1); int size = width*height; int* intSrc=(int*)malloc32(size/4,HEAP_3); int* intDst=intSrc; free32(intSrc); CSobel sobel(width, height); // Check memory allocation if (sobel.isReady==false || intSrc ==0 ){ ncl_hostSync(0xDEADB00F); // send error to host return -1; } else ncl_hostSync(0x600DB00F); // send ok to host ncl_hostSync((int)extSrc); // Send source buffer address to host ncl_hostSync((int)extDst); // Send result buffer address to host clock_t t0,t1; int counter=0; // frame counter while(1){ // Start sobel in loop ncl_hostSync(counter); // Wait source buffer till is ready nmppsCopy_8u((nm8u*)extSrc,(nm8u*)intSrc,size); t0=clock(); sobel.filter((unsigned char*)intSrc,(unsigned char*)intDst); t1=clock(); nmppsCopy_8u((nm8u*)intDst,(nm8u*)extDst,size); ncl_hostSync(t1-t0); // Send elapsed time counter++; } ncl_hostSync(0xDEADB00F); free32(extSrc); free32(extDst); return 1; }
void SobelTestNtt(const std::string &aName) { Tiff_Im aTF = Tiff_Im::StdConvGen(aName,1,true); Pt2di aSz = aTF.sz(); Im2D_REAL4 aI0(aSz.x,aSz.y); ELISE_COPY( aTF.all_pts(),aTF.in(),aI0.out()); Video_Win * aW=0; // aW = Video_Win::PtrWStd(aSz); if (aW) { ELISE_COPY(aW->all_pts(),Min(255,aI0.in()/256.0),aW->ogray()); aW->clik_in(); } Fonc_Num aF1 = sobel(aI0.in_proj()); Fonc_Num aF2 = aI0.in_proj(); for (int aK=0 ; aK<3 ; aK++) aF2 = rect_som(aF2,1) / 9.0; aF2 = sobel(aF2); if (aW) { ELISE_COPY(aW->all_pts(),Min(255, 200 * (aF1/Max(aF2,1e-7))),aW->ogray()); aW->clik_in(); } double aSF1,aSF2,aSomPts; ELISE_COPY(aI0.all_pts(),Virgule(aF1,aF2,1.0),Virgule(sigma(aSF1),sigma(aSF2),sigma(aSomPts))); std::cout << "Indice " << aSF1 / aSF2 << "\n"; }
int main() { //---------- start nm program ------------ int fromHost=ncl_hostSync(0xC0DE6406); // send handshake to host if (fromHost!=0xC0DE0086){ // get handshake from host return -1; } // Get image parameters from host int width = ncl_hostSync(0); int height= ncl_hostSync(1); int size = width*height; // Check memory allocation if (src ==0 || dst==0){ ncl_hostSync(0xDEADB00F); // send error to host return -1; } else ncl_hostSync(0x600DB00F); // send ok to host ncl_hostSync((int)src); // Send source buffer address to host ncl_hostSync((int)dst); // Send result buffer address to host clock_t t0,t1; int counter=0; // frame counter bool isOk; while(1){ // Start sobel in loop ncl_hostSync(counter); // Wait source buffer till is ready t0=clock(); isOk=sobel((unsigned char*)src,(unsigned char*)dst, width, height); t1=clock(); if (isOk==false ) break; ncl_hostSync(t1-t0); // Send elapsed time counter++; } ncl_hostSync(0xDEADB00F); free(src); free(dst); return 1; }
QImage ImgConvolutions::applyConvolution(convolutionList op, QImage *img1, int filterSize){ switch(op){ case CONV_PASABAJOS: return pasaBajos(img1, filterSize); case CONV_BARTLETT: case CONV_GAUSSIANO: case CONV_SHARPEN: return sharpen(img1, filterSize); case CONV_MOTIONBLUR: return motionBlur(img1, filterSize); case CONV_PASAALTOS: return pasaAltos(img1, filterSize); case CONV_SOBEL: return sobel(img1); case CONV_PA_LPv4: return laplacianov4(img1); case CONV_PA_LPv8: return laplacianov8(img1); } return QImage(); }
PNM* MapNormal::transform() { int width = image->width(), height = image->height(); double strength = getParameter("strength").toDouble(); PNM* newImage = new PNM(width, height, image->format()); PNM* tempImage = MapHeight(image).transform(); EdgeSobel sobel(tempImage); math::matrix<float>* Gx = sobel.rawHorizontalDetection(); math::matrix<float>* Gy = sobel.rawVerticalDetection(); newImage = new PNM(width, height, QImage::Format_RGB32); for(int i=0; i<width; i++) { for(int j=0; j<height; j++) { double dx = (*Gx)(i,j)/PIXEL_VAL_MAX; double dy = (*Gy)(i,j)/PIXEL_VAL_MAX; double dz = 1/strength; double length = sqrt(dx*dx + dy*dy + dz*dz); dx = dx/length; dy = dy/length; double dZ = dz/length; double t = 255/strength; dx = (dx + 1.0)* t; dy = (dy + 1.0)* t; dZ = (dZ + 1.0)* t; newImage->setPixel(i,j,qRgb(dx,dy,dZ)); } } return newImage; }
int main() { if(!VS_Init()) // Init vshell return 0; if(!VS_Bind("../../../input/bugs720x576x20.avi")) // Input video stream return 0; int width =VS_GetWidth (VS_SOURCE); // Get width of video frame int height=VS_GetHeight(VS_SOURCE); // Get height of video frame int size =width*height; VS_CreateImage("Source Image", 1, width, height, VS_RGB8, 0); // Create window for grayscale drawing of 8-bit source image VS_CreateImage("Sobel Image", 2, width, height, VS_RGB8, 0); // Create window for grayscale drawing of 8-bit result image NmppsFrame_8u srcFrame; NmppsFrame_8u dstFrame; unsigned char* srcImg8=(unsigned char*) nmppsMallocFrame_8u(size,width,&srcFrame); // Allocate source image buffer with guard fields of two rows unsigned char* dstImg8=(unsigned char*) nmppsMallocFrame_8u(size,width,&dstFrame); // Allocate result image buffer CSobel sobel(width, height); while(VS_Run()) { VS_GetGrayData(VS_SOURCE, srcImg8); // Get image from video stream VS_SetData(1, srcImg8); // Put source image in window 1 sobel.filter(srcImg8, dstImg8); VS_SetData(2, dstImg8); VS_Draw(VS_DRAW_ALL); } nmppsFree(srcFrame.pull); // Free source image buffer nmppsFree(dstFrame.pull); // Free result image buffer return 0; }
int main() { BMP srcBMP; srcBMP.ReadFromFile("../../../input/lena.bmp"); BMP dstBMP(srcBMP); int width =srcBMP.TellWidth(); int height=srcBMP.TellHeight(); unsigned char* srcData= new unsigned char[width*height]; unsigned char* dstData= new unsigned char[width*height]; BMP2graydata(srcBMP, srcData); sobel( srcData, dstData, width, height); graydata2BMP(dstData, dstBMP); dstBMP.WriteToFile("dst.bmp"); delete srcData; delete dstData; return 0; }
bool IPLGradientOperator::processInputData(IPLImage* image , int, bool) { // delete previous result delete _result; _result = new IPLOrientedImage(image->width(), image->height()); // get properties int algorithm = getProcessPropertyInt("algorithm"); switch (algorithm){ case 0: default: return fastGradient(image); case 1: return roberts(image); case 2: return sobel(image); case 3: return cubicSpline(image); } //make compiler happy... return false; }
int main() { int width ; int height; // parse pgm header int src_pgm_header_len=read_pgm_header(src_pgm_file,width,height); if (src_pgm_header_len==0) { width=128; // use default value if pgm-header is invalid height=128; // use default value if pgm-header is invalid } nm8u* src=nmppsAddr_8u((nm8u*)src_pgm_file,src_pgm_header_len); int dst_pgm_header_len=save_pgm_header(dst_pgm_file,width,height," Created By RC-Module(2015)"); nm8u* dst=nmppsAddr_8u((nm8u*)dst_pgm_file,dst_pgm_header_len); // Sobel filtration CBaseSobel sobel(width, height); if (!sobel.isReady) return -1; clock_t t0=clock(); sobel.filter(src,dst); clock_t t1=clock(); return t1-t0; }
int main(int argc, char *argv[]) { if (argc != 4) { cout << "Usage: " << argv[0] << " cpu|gpu out_func out_prefix" << endl; return 1; } ImageParam input(UInt(8), 3, "input"); Func clamped("clamped"), grayscale("grayscale"); Func g_x("g_x"), g_y("g_y"), g_mag("g_mag"); Func sobel("sobel"); Var c("c"), x("x"), y("y"); // Algorithm clamped(x, y, c) = input( clamp(x, 0, input.width()-1), clamp(y, 0, input.height()-1), c) / 255.f; grayscale(x, y) = clamped(x, y, 0)*0.299f + clamped(x, y, 1)*0.587f + clamped(x, y, 2)*0.114f; Image<int16_t> kernel(3, 3); kernel(0, 0) = -1; kernel(0, 1) = -2; kernel(0, 2) = -1; kernel(1, 0) = 0; kernel(1, 1) = 0; kernel(1, 2) = 0; kernel(2, 0) = 1; kernel(2, 1) = 2; kernel(2, 2) = 1; RDom r(kernel); g_x(x, y) += kernel(r.x, r.y) * grayscale(x + r.x - 1, y + r.y - 1); g_y(x, y) += kernel(r.y, r.x) * grayscale(x + r.x - 1, y + r.y - 1); g_mag(x, y) = sqrt(g_x(x, y)*g_x(x, y) + g_y(x, y)*g_y(x, y)); sobel(x, y, c) = select(c==3, 255, u8(clamp(g_mag(x, y), 0, 1)*255)); // Channel order input.set_stride(0, 4); input.set_extent(2, 4); sobel.reorder_storage(c, x, y); sobel.output_buffer().set_stride(0, 4); sobel.output_buffer().set_extent(2, 4); // Schedules if (!strcmp(argv[1], "cpu")) { sobel.parallel(y).vectorize(c, 4); } else if (!strcmp(argv[1], "gpu")) { sobel.cuda_tile(x, y, 16, 4); } else { cout << "Invalid schedule type '" << argv[1] << "'" << endl; return 1; } compile(sobel, input, argv[2], argv[3]); return 0; }
int main(int argc, char **argv) { Ics_Error icserr; ICS* ics; size_t dims[ICS_MAXDIM]; int ndims; int i,j; Ics_DataType dt; char fname[32]; char cmdlin[256]; /* TODO */ pix_type *prev; /* previous frame */ unsigned char *buf; /* 8-bit buffer */ int startframe,endframe; int *tmp; int *probb; int *prob; int *imsob; FILE *f; int w,h; int err; /* unsigned char *wsh; */ int markx[2],marky[2]; unsigned char *wsh; if(argc < 2){ printf(" usage: edgeprob <filename>.ics <prob.pgm> [startframe [endframe]] [-e cutoff]\n"); printf(" example: edgeprob livecell.ics livecell1.pgm 30 35 e\n"); printf(" center of cell should be marked with single dot of intensity 128\n"); printf(" does all frames if start frame not specified\n"); return 0; } /* Open file */ icserr = IcsOpen(&ics, argv[1], "r"); ICS_CHECK(icserr); #ifdef DEBUG_PRINT printf("ics file loaded.\n"); #endif /* Sniff out file; make sure it is compatible with our prog */ icserr = IcsGetLayout(ics, &dt, &ndims, dims); ICS_CHECK(icserr); if(dt != Ics_uint16){ printf("Sorry, image modes other than 16-bit (unsigned) "); printf("not supported at the moment.\n"); return 0; } /* number of frames specified */ startframe = 0; endframe = dims[3]; if(argc >= 4){ startframe = strtol(argv[3],NULL,0); if(startframe > dims[3]) startframe = dims[3]; if(startframe < 0){ printf("Start frame number must be non-negative.\n"); return 1; } if(argc >= 5){ endframe = strtol(argv[4],NULL,0); if(endframe < startframe){ printf("End frame number must be greater than start.\n"); return 2; } if(endframe > dims[3]) endframe = dims[3]; } } #ifdef DEBUG_PRINT printf("dimensions: "); for(i=0;i<ndims;i++) printf("%ld ", dims[i]); printf("data type: %d \n", dt); #endif /* TODO: warning if dimensions look non-standard */ /* allocate space before reading */ /* Only allocate for one frame; allows images with many frames * to be loaded without much memory, unlike some programs * (I'm looking at you, ics_opener/ImageJ ! */ prev = (pix_type *) malloc(dims[1]*dims[2]*sizeof(pix_type)); buf = (unsigned char *)malloc(dims[1]*dims[2]*sizeof(unsigned char)); tmp = (int *) malloc(dims[1]*dims[2]*sizeof(int)); probb = (int *) malloc(dims[1]*dims[2]*sizeof(int)); prob = (int *) malloc(dims[1]*dims[2]*sizeof(int)); imsob = (int *) malloc(dims[1]*dims[2]*sizeof(int)); wsh = (unsigned char *)malloc(dims[1]*dims[2]*sizeof(unsigned char)); if((!prev)||(!buf)||(!tmp)||(!probb)||(!prob)||(!imsob)||(!wsh)) { printf("Couldn't allocate enough memory.\n"); return 1; } /* load probabilities */ f = fopen(argv[2],"r"); if(!f){ printf("Error: could not open file %s\n",argv[2]); return 10; } if((err = load_data(f, &prob, &w, &h))){ printf("Error: %s: incorrect or corrupt pgm file.\n",argv[2]); return 11; } if((w!=dims[1])||(h!=dims[2])){ printf("Error: Size mismatch. ICS data are %ldx%ld but probability data are %dx%d\n", dims[1],dims[2],w,h); return 9; } fclose(f); /* obtain marker from prob image */ markx[0]=10; marky[0]=10; markx[1]=markx[0]; marky[1]=marky[0]; for(j=0;j<dims[2];j++){ for(i=0;i<dims[1];i++){ if(prob[j*dims[1] + i]==128){ markx[1]=i; marky[1]=j; } } } if((markx[0]==markx[1])&&(marky[1]==marky[0])){ printf("Error: marker not found in prob image.\n"); printf("(should be single pixel with intensity 128)\n"); return 8; } printf("tracking...\n"); /* read sequentially from file. */ /* Each call to IcsGetDataBlock proceeds from the end of the last */ for(i=0;i<endframe;i++){ icserr = IcsGetDataBlock(ics, prev, dims[1]*dims[2]*2); ICS_CHECK(icserr); if(i>=startframe){ /* blur probabilities */ memcpy(probb, prob, sizeof(int)*dims[1]*dims[2]); blur_diffuse(probb, tmp, dims[1], dims[2]); blur_diffuse(tmp, probb, dims[1], dims[2]); blur_cusp(probb, tmp, dims[1], dims[2], 210); blur_diffuse(probb, tmp, dims[1], dims[2]); blur_diffuse(tmp, probb, dims[1], dims[2]); /* come up with new probabilities */ im2int(prev, tmp, dims[1], dims[2]); sobel(tmp, imsob, dims[1], dims[2]); /* convert to probability */ for(j=0;j<dims[1]*dims[2];j++){ imsob[j] >>= 4; if(imsob[j]>255) imsob[j]=255; } /* mix them up */ combine_prob(probb, imsob, prob, dims[1], dims[2]); normalize_prob(prob, dims[1], dims[2]); /* watershed to 'collapse' probabilities */ /*watershed(prob, wsh, tmp, dims[1], dims[2], markx, marky, 2); for(j=0;j<dims[1]*dims[2];j++){ wsh[j] = (wsh[j]==2 ? 8 : 0); }*/ watershed_rep(prob, buf, tmp, dims[1], dims[2], markx, marky, 2, wsh, 8, 24.0); center_of_mass(wsh, dims[1], dims[2], 8, markx, marky); hardedge(wsh, buf, dims[1], dims[2]); /* now combine the existing probabilities with the ones from hardedge */ for(j=0;j<dims[1]*dims[2];j++){ if(buf[j]==255) prob[j]=(3*255+prob[j])/4; } for(j=0;j<dims[1]*dims[2];j++) buf[j]=prob[j]; printf("frame %d\n", i); sprintf(fname, "prob_%04d.png", i); export_8bit_pgm(buf, dims[1], dims[2], "tmp.pgm"); sprintf(cmdlin, "pnmtopng -compression 1 < tmp.pgm > %s", fname); system(cmdlin); } }
int main(int argc, char *argv[]) { IplImage* img = 0; int height,width,step,channels; unsigned char *data; // load an image img= cvLoadImage("kantai.png"); if(!img){ printf("Could not load image file: %s\n",argv[1]); exit(0); } // get the image data height = img->height; width = img->width; step = img->widthStep; channels = img->nChannels; data = (uchar *)img->imageData; printf("Processing a %dx%d image with %d channels\n",height,width,channels); printf("step = %d\n", step); IplImage* imgGrayscale = cvCreateImage(cvGetSize(img), IPL_DEPTH_8U, 1); // 8-bit grayscale is enough. // convert to grayscale. cvCvtColor(img, imgGrayscale, CV_BGR2GRAY); // Create an image for the outputs IplImage* imgSobelX = cvCreateImage( cvGetSize(img), IPL_DEPTH_32F, 1 ); // to prevent overflow. IplImage* imgSobelY = cvCreateImage( cvGetSize(img), IPL_DEPTH_32F, 1 ); IplImage* imgSobelAdded = cvCreateImage( cvGetSize(img), IPL_DEPTH_32F, 1 ); IplImage* imgSobel = cvCreateImage( cvGetSize(img), IPL_DEPTH_8U, 1 ); // final image is enough to be an 8-bit plane. // Sobel cvSobel(imgGrayscale, imgSobelX, 1, 0, 3); cvSobel(imgGrayscale, imgSobelY, 0, 1, 3); cvAdd(imgSobelX, imgSobelY, imgSobelAdded); cvConvertScaleAbs(imgSobelAdded, imgSobel); //scaled to 8-bit level; important for visibility. //----------------------- OULINE EXTRACTION ------------------------------- // Normal diff IplImage* imgNormDiff = cvCreateImage(cvGetSize(img), 8, 1); cvCopy(imgGrayscale,imgNormDiff); norm_diff(imgNormDiff); // Roberts IplImage* imgRoberts = cvCreateImage(cvGetSize(img), 8, 1); cvCopy(imgGrayscale,imgRoberts); roberts(imgRoberts); // Sobel IplImage* imgSobel2 = cvCreateImage(cvGetSize(img), 8, 1); cvCopy(imgGrayscale,imgSobel2); sobel(imgSobel2); // Laplacian IplImage* imgLap = cvCreateImage(cvGetSize(img), 8, 1); cvCopy(imgGrayscale,imgLap); laplacian(imgLap); //--------------------------- ENHANCEMENT -------------------------------- // Laplacian IplImage* imgLap2 = cvCreateImage(cvGetSize(img), 8, 3); IplImage* imgRed = cvCreateImage(cvGetSize(img), 8, 1); IplImage* imgGreen = cvCreateImage(cvGetSize(img), 8, 1); IplImage* imgBlue = cvCreateImage(cvGetSize(img), 8, 1); cvSplit(img, imgRed, imgGreen, imgBlue, NULL); laplacian2(imgBlue); laplacian2(imgGreen); laplacian2(imgRed); cvMerge(imgRed,imgGreen,imgBlue, NULL, imgLap2); // Variant IplImage* imgVariant = cvCreateImage(cvGetSize(img), 8, 3); IplImage* imgRed2 = cvCreateImage(cvGetSize(img), 8, 1); IplImage* imgGreen2 = cvCreateImage(cvGetSize(img), 8, 1); IplImage* imgBlue2 = cvCreateImage(cvGetSize(img), 8, 1); cvSplit(img, imgRed2, imgGreen2, imgBlue2, NULL); variant(imgBlue2); variant(imgGreen2); variant(imgRed2); cvMerge(imgRed2,imgGreen2,imgBlue2, NULL, imgVariant); // Sobel IplImage* imgSobel3 = cvCreateImage(cvGetSize(img), 8, 3); IplImage* imgRed3 = cvCreateImage(cvGetSize(img), 8, 1); IplImage* imgGreen3 = cvCreateImage(cvGetSize(img), 8, 1); IplImage* imgBlue3 = cvCreateImage(cvGetSize(img), 8, 1); cvSplit(img, imgRed3, imgGreen3, imgBlue3, NULL); sobel2(imgBlue3); sobel2(imgGreen3); sobel2(imgRed3); cvMerge(imgRed3,imgGreen3,imgBlue3, NULL, imgSobel3); // create a window cvNamedWindow("Original", CV_WINDOW_KEEPRATIO); cvNamedWindow("Normal different line", CV_WINDOW_KEEPRATIO); cvNamedWindow("Roberts line", CV_WINDOW_FREERATIO); cvNamedWindow("Sobel line", CV_WINDOW_FREERATIO); cvNamedWindow("Laplacian line", CV_WINDOW_KEEPRATIO); cvNamedWindow("Laplacian Color", CV_WINDOW_KEEPRATIO); cvNamedWindow("Variant", CV_WINDOW_KEEPRATIO); cvNamedWindow("Sobel", CV_WINDOW_KEEPRATIO); /*cvNamedWindow( "Sobel-x" ); cvNamedWindow( "Sobel-y" ); cvNamedWindow( "Sobel-Added" ); cvNamedWindow( "Sobel-Added (scaled)" );*/ // show the image cvShowImage("Original", img); cvShowImage("Normal different line", imgNormDiff); cvShowImage("Roberts line",imgRoberts); cvShowImage("Sobel line", imgSobel2); cvShowImage("Laplacian line", imgLap); cvShowImage("Laplacian Color", imgLap2); cvShowImage("Variant", imgVariant); cvShowImage("Sobel", imgSobel3); /*cvShowImage("Sobel-x", imgSobelX); cvShowImage("Sobel-y", imgSobelY); cvShowImage("Sobel-Added", imgSobelAdded); cvShowImage("Sobel-Added (scaled)", imgSobel);*/ // wait for a key cvWaitKey(0); // release the image cvReleaseImage(&img); cvReleaseImage(&imgGrayscale); cvReleaseImage(&imgNormDiff); cvReleaseImage(&imgRoberts); cvReleaseImage(&imgSobel2); cvReleaseImage(&imgLap); cvReleaseImage(&imgLap2); cvReleaseImage(&imgVariant); cvReleaseImage(&imgSobel3); cvReleaseImage(&imgSobelX); cvReleaseImage(&imgSobelY); cvReleaseImage(&imgSobelAdded); cvReleaseImage(&imgSobel); return 0; }
int main(int argc, char **argv) { Ics_Error icserr; ICS* ics; size_t dims[ICS_MAXDIM]; int ndims; int i,j; Ics_DataType dt; /* TODO */ pix_type *prev; /* previous frame */ unsigned char *buf; /* 8-bit buffer */ int startframe,endframe; int *tmp1,*tmp2,*var,*sob; int xmark[2],ymark[2]; unsigned char *wsh; FILE *comf; char fname[64],cmdlin[128]; if(argc < 4){ printf("usage: nucfollow <filename>.ics <x> <y> [startframe [endframe]] [-e cutoff]\n"); printf("(x,y) is the coordinate of the nucleus at first iteration.\n"); printf("example: nucfollow livecell.ics 400 300 30\n"); printf("extracts all frames if start frame not specified\n"); return 0; } /* Open file */ icserr = IcsOpen(&ics, argv[1], "r"); ICS_CHECK(icserr); #ifdef DEBUG_PRINT printf("ics file loaded.\n"); #endif /* Sniff out file; make sure it is compatible with our prog */ icserr = IcsGetLayout(ics, &dt, &ndims, dims); ICS_CHECK(icserr); if(dt != Ics_uint16){ printf("Sorry, image modes other than 16-bit (unsigned) "); printf("not supported at the moment.\n"); return 0; } /* marker */ xmark[0] = 10; ymark[0] = 10; xmark[1] = strtol(argv[2],NULL,0); ymark[1] = strtol(argv[3],NULL,0); /* number of frames specified */ startframe = 0; endframe = 1; if(argc >= 5){ startframe = strtol(argv[4],NULL,0); if(startframe > dims[3]) startframe = dims[3]; if(startframe < 0){ printf("Start frame number must be non-negative.\n"); return 1; } if(argc >= 6){ endframe = strtol(argv[5],NULL,0); if(endframe < startframe){ printf("End frame number must be greater than start.\n"); return 2; } if(endframe > dims[3]) endframe = dims[3]; } else { endframe = startframe+1; } } #ifdef DEBUG_PRINT printf("dimensions: "); for(i=0;i<ndims;i++) printf("%ld ", dims[i]); printf("data type: %d \n", dt); #endif /* TODO: warning if dimensions look non-standard */ /* allocate space before reading */ /* Only allocate for one frame; allows images with many frames * to be loaded without much memory, unlike some programs * (I'm looking at you, ics_opener/ImageJ ! */ prev = malloc(dims[1]*dims[2]*sizeof(pix_type)); buf = malloc(dims[1]*dims[2]*sizeof(unsigned char)); tmp1 = (int *)malloc(dims[1]*dims[2]*sizeof(int)); tmp2 = (int *)malloc(dims[1]*dims[2]*sizeof(int)); var = (int *)malloc(dims[1]*dims[2]*sizeof(int)); sob = (int *)malloc(dims[1]*dims[2]*sizeof(int)); wsh = (unsigned char*)malloc(dims[1]*dims[2]*sizeof(int)); if((!prev)||(!buf)||(!tmp1)||(!tmp2)||(!var)||(!sob)||(!wsh)) { printf("Couldn't allocate enough memory.\n"); return 1; } /* open CoM file for output */ comf = fopen("comf.txt","w"); if(!comf){ printf("error: couldn't open comf.txt to write center of mass data!\n"); return 22; } fprintf(comf,"frame x y\n"); /* legend */ printf("tracking...\n"); /* read sequentially from file. */ /* Each call to IcsGetDataBlock proceeds from the end of the last */ for(i=0;i<endframe;i++){ icserr = IcsGetDataBlock(ics, prev, dims[1]*dims[2]*2); ICS_CHECK(icserr); if(i <startframe) continue; /* we are at the desired frame sequence. */ /* variance filter */ printf("frame %d\n", i); printf(" Variance filter...\n"); #if 0 if(variance(prev,var,tmp1,tmp2,dims[1],dims[2],1.0,4.0,12)) printf("Variance filter error!\n"); #endif fast_variance(prev, var, tmp1, dims[1], dims[2]); printf(" Cusp blur...\n"); blur_cusp(var,tmp1,dims[1],dims[2],230); /*printf("Diffusion blur...\n"); blur_diffuse(var,tmp2,dims[1],dims[2]); blur_diffuse(tmp2,var,dims[1],dims[2]); */ int maxo; maxo=0; for(j=0;j<dims[1]*dims[2];j++) if(var[j]>maxo) maxo=var[j]; printf(" maxo: %d\n", maxo); printf(" Sobel edge detection...\n"); sobel(var, sob, dims[1], dims[2]); /* reduce the output of sobel before watershed; * this greatly reduces processing time */ /* TODO: infer this from the actual histographic data */ for(j=0;j<dims[1]*dims[2];j++) sob[j] /= 10; for(j=0;j<dims[1]*dims[2];j++) if(sob[j]>255) sob[j]=255; printf(" watershed assembly...\n"); if(watershed_rep(sob, wsh, tmp1, dims[1], dims[2], xmark, ymark, 2, buf, 8, 8.0)){ printf(" error during watershed!\n"); return 1; } /* print center of mass to file */ fprintf(comf,"%d %d %d\n", i, xmark[1], ymark[1]); /* modify mark */ if(center_of_mass(buf, dims[1], dims[2], 8, xmark+1, ymark+1)){ printf(" zero identified regions!\n aborting.\n"); break; /* abort so we can at least see the results */ } /* output superimposed image */ for(j=0;j<dims[1]*dims[2];j++) wsh[j] = prev[j] >> 4; hardedge(buf, wsh, dims[1], dims[2]); sprintf(fname,"vesw_sup_%04d.pgm",i); export_8bit_pgm(wsh, dims[1], dims[2], fname); sprintf(cmdlin,"pnmtopng < %s > vesw_sup_%04d.png\nrm %s\n", fname, i, fname); if(system(cmdlin)){ printf("Error during NetPbm invoke!\n"); return 55; } } buf[ymark[1]*dims[1] + xmark[1]]=255-buf[ymark[1]*dims[1] + xmark[1]]; /* mark next CoM */ export_8bit_pgm(buf, dims[1], dims[2], "vesw.pgm"); for(j=0;j<dims[1]*dims[2];j++) buf[j] = var[j]/64; export_8bit_pgm(buf, dims[1], dims[2], "ve.pgm"); for(j=0;j<dims[1]*dims[2];j++) buf[j] = sob[j]/8; export_8bit_pgm(buf, dims[1], dims[2], "ves.pgm"); fclose(comf); /* no need to free memory; that's just silly */ IcsClose(ics); return 0; }
void filter(double y0, double y1, double y2, double y3, double y4, double y5, double y6, double y7, double y8, double y9, double y10, double y11, double y12, double y13, double y14, double y15, double y16, double y17, double y18, double y19, double* x1, double* x2, double* x3, double* x4, double* x5, double* x6, double* x7, double* x8, double* x9, double* x10, double* x11, double* x12, double* x13, double* x14, double* x15, double* x16, double* x17, double* x18, double* x19) { *x1=sobel(y0,y1); *x2=sobel(y1,y2); *x3=sobel(y2,y3); *x4=sobel(y3,y4); *x5=sobel(y4,y5); *x6=sobel(y5,y6); *x7=sobel(y6,y7); *x8=sobel(y7,y8); *x9=sobel(y8,y9); *x10=sobel(y9,y10); *x11=sobel(y10,y11); *x12=sobel(y11,y12); *x13=sobel(y12,y13); *x14=sobel(y13,y14); *x15=sobel(y14,y15); *x16=sobel(y15,y16); *x17=sobel(y16,y17); *x18=sobel(y17,y18); *x19=sobel(y18,y19); }
QImage NormalmapGenerator::calculateNormalmap(const QImage& input, Kernel kernel, double strength, bool invert, bool tileable, bool keepLargeDetail, int largeDetailScale, double largeDetailHeight) { this->tileable = tileable; this->intensity = IntensityMap(input, mode, redMultiplier, greenMultiplier, blueMultiplier, alphaMultiplier); if(!invert) { // The default "non-inverted" normalmap looks wrong in renderers, // so I use inversion by default intensity.invert(); } QImage result(input.width(), input.height(), QImage::Format_ARGB32); // optimization double strengthInv = 1.0 / strength; #pragma omp parallel for // OpenMP //code from http://stackoverflow.com/a/2368794 for(int y = 0; y < input.height(); y++) { QRgb *scanline = (QRgb*) result.scanLine(y); for(int x = 0; x < input.width(); x++) { const double topLeft = intensity.at(handleEdges(x - 1, input.width()), handleEdges(y - 1, input.height())); const double top = intensity.at(handleEdges(x - 1, input.width()), handleEdges(y, input.height())); const double topRight = intensity.at(handleEdges(x - 1, input.width()), handleEdges(y + 1, input.height())); const double right = intensity.at(handleEdges(x, input.width()), handleEdges(y + 1, input.height())); const double bottomRight = intensity.at(handleEdges(x + 1, input.width()), handleEdges(y + 1, input.height())); const double bottom = intensity.at(handleEdges(x + 1, input.width()), handleEdges(y, input.height())); const double bottomLeft = intensity.at(handleEdges(x + 1, input.width()), handleEdges(y - 1, input.height())); const double left = intensity.at(handleEdges(x, input.width()), handleEdges(y - 1, input.height())); const double convolution_kernel[3][3] = {{topLeft, top, topRight}, {left, 0.0, right}, {bottomLeft, bottom, bottomRight}}; QVector3D normal(0, 0, 0); if(kernel == SOBEL) normal = sobel(convolution_kernel, strengthInv); else if(kernel == PREWITT) normal = prewitt(convolution_kernel, strengthInv); scanline[x] = qRgb(mapComponent(normal.x()), mapComponent(normal.y()), mapComponent(normal.z())); } } if(keepLargeDetail) { //generate a second normalmap from a downscaled input image, then mix both normalmaps int largeDetailMapWidth = (int) (((double)input.width() / 100.0) * largeDetailScale); int largeDetailMapHeight = (int) (((double)input.height() / 100.0) * largeDetailScale); //create downscaled version of input QImage inputScaled = input.scaled(largeDetailMapWidth, largeDetailMapHeight, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); //compute downscaled normalmap QImage largeDetailMap = calculateNormalmap(inputScaled, kernel, largeDetailHeight, invert, tileable, false, 0, 0.0); //scale map up largeDetailMap = largeDetailMap.scaled(input.width(), input.height(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation); #pragma omp parallel for // OpenMP //mix the normalmaps for(int y = 0; y < input.height(); y++) { QRgb *scanlineResult = (QRgb*) result.scanLine(y); QRgb *scanlineLargeDetail = (QRgb*) largeDetailMap.scanLine(y); for(int x = 0; x < input.width(); x++) { const QRgb colorResult = scanlineResult[x]; const QRgb colorLargeDetail = scanlineLargeDetail[x]; const int r = blendSoftLight(qRed(colorResult), qRed(colorLargeDetail)); const int g = blendSoftLight(qGreen(colorResult), qGreen(colorLargeDetail)); const int b = blendSoftLight(qBlue(colorResult), qBlue(colorLargeDetail)); scanlineResult[x] = qRgb(r, g, b); } } } return result; }
void MainWindow::sobelEdges() { image = sobel(image); setImages(); }
int main() { // Init VDU unsigned Y0=0xC0000000; unsigned Y1=0xC0000000; nmppsSet_8u((nm8u*) ARM2NM(0xC0000000), 128, 720*576*2); nmppsSet_8u((nm8u*) ARM2NM(0xC0000000), 255, 720*576/2); Start_VDU_SD( Y0, Y1) ; //---------- start nm program ------------ int fromHost=ncl_hostSync(0xC0DE6406); // send handshake to host if (fromHost!=0xC0DE0086){ // get handshake from host return -1; } // Get image parameters from host int width = ncl_hostSync(0); int height= ncl_hostSync(1); int size = width*height; // Allocate memory for 8-bit source and result images in shared memory nm8u* dst=(nm8u*)ARM2NM(0xC0000000); // VDU DDR int frames=0;// number of loaded frames in DDR int maxFrames=128*1024*1024/size; nm8u* video=(nm8u*)ARM2NM(0x40000000); // VUDEO-STREAM DDR CSobel sobel(width, height); // Check memory allocation if (sobel.isReady==false){ ncl_hostSync(0xDEADB00F); // send error to host return -1; } else ncl_hostSync(0x600DB00F); // send ok to host ncl_hostSync((int)&frames); // Send frame addr to host ncl_hostSync((int)video); // Send video buffer addr to host clock_t t0,t1; char str[128]; int counter=0; // frame counter while(1){ // Start sobel in loop for(int i=0; i<MIN(maxFrames-1,frames); i++){ nm8u* src=nmppsAddr_8u(video,i*size); t0=clock(); sobel.filter(src,dst); t1=clock(); unsigned t=t1-t0; sprintf(str,"%d clocks per frame, %.2f clocks per pixel, %.2f fps", t, 1.0*t/size, 320000000.0/t); IMG_Print8x15( str, dst, width, 10, 10 , 255, 0); sleep(1000); } counter++; } return 1; }
static void run (const gchar *name, gint nparams, const GimpParam *param, gint *nreturn_vals, GimpParam **return_vals) { static GimpParam values[2]; GimpDrawable *drawable; GimpRunMode run_mode; GimpPDBStatusType status = GIMP_PDB_SUCCESS; run_mode = param[0].data.d_int32; INIT_I18N (); *nreturn_vals = 1; *return_vals = values; values[0].type = GIMP_PDB_STATUS; values[0].data.d_status = status; /* Get the specified drawable */ drawable = gimp_drawable_get (param[2].data.d_drawable); gimp_tile_cache_ntiles (2 * drawable->ntile_cols); switch (run_mode) { case GIMP_RUN_INTERACTIVE: /* Possibly retrieve data */ gimp_get_data (PLUG_IN_PROC, &bvals); /* First acquire information with a dialog */ if (! sobel_dialog (drawable)) return; break; case GIMP_RUN_NONINTERACTIVE: /* Make sure all the arguments are there! */ if (nparams != 6) { status = GIMP_PDB_CALLING_ERROR; } else { bvals.horizontal = (param[4].data.d_int32) ? TRUE : FALSE; bvals.vertical = (param[5].data.d_int32) ? TRUE : FALSE; bvals.keep_sign = (param[6].data.d_int32) ? TRUE : FALSE; } break; case GIMP_RUN_WITH_LAST_VALS: /* Possibly retrieve data */ gimp_get_data (PLUG_IN_PROC, &bvals); break; default: break; } /* Make sure that the drawable is gray or RGB color */ if (gimp_drawable_is_rgb (drawable->drawable_id) || gimp_drawable_is_gray (drawable->drawable_id)) { sobel (drawable, bvals.horizontal, bvals.vertical, bvals.keep_sign, NULL); if (run_mode != GIMP_RUN_NONINTERACTIVE) gimp_displays_flush (); /* Store data */ if (run_mode == GIMP_RUN_INTERACTIVE) gimp_set_data (PLUG_IN_PROC, &bvals, sizeof (bvals)); } else { status = GIMP_PDB_EXECUTION_ERROR; *nreturn_vals = 2; values[1].type = GIMP_PDB_STRING; values[1].data.d_string = _("Cannot operate on indexed color images."); } gimp_drawable_detach (drawable); values[0].data.d_status = status; }
PPMImage PerformAA(const PPMImage& original, const PPMImage& filtered) { NetPBMLoader loader; PPMImage recovered(original.getLength(), original.getWidth()); PPMImage maxVarDir(original.getLength(), original.getWidth()); PPMImage sobel(original.getLength(), original.getWidth()); for(int i = 0; i < recovered.getLength(); ++i) { for(int j = 0; j < recovered.getWidth(); ++j) { // don't treat border pixels if(i == 0 || j == 0 || i == recovered.getLength()-1 || j == recovered.getWidth()-1) { recovered(i,j) = filtered(i,j); continue; } PPMImage neighbors(3,3); PPMImage neighborsAliased(3,3); Vector3D pixel = original(i,j); Vector3D pixelAlias = filtered(i,j); // colors are changing most rapidly considering this direction Vector3D varDir; // the distance vector from the average value of neighbors Vector3D dAverage[9]; // the average value computed considering the neighbors Vector3D average; // parameters to compute recovery float alpha = 0; float beta = 0; float dp = 0; float Gd = 0; float ep = 0; float Ge = 0; // construct neighbors of aliased and original images for(int k = i-1; k <= i+1; ++k) { for(int l = j-1; l <= j+1; ++l) { neighbors((k-i)+1, (l-j)+1) = original(k,l); neighborsAliased((k-i)+1, (l-j)+1) = filtered(k,l); } } // compute the average for(int k = 0; k < neighbors.getLength(); ++k) { for(int l = 0; l < neighbors.getWidth(); ++l) { average += neighbors(k,l); } } average /= neighbors.getSize(); // compute the distance from the average color value for(int k = 0; k < neighbors.getLength(); ++k) { for(int l = 0; l < neighbors.getWidth(); ++l) { dAverage[k*neighbors.getLength()+l] = neighbors(k,l) - average; } } varDir = Vector3D(average.normalize() + EPSILON); EM(dAverage, 3, varDir, neighbors.getSize()); Vector2D maxColorPos; Vector2D minColorPos; // compute the two maximum colors along the straight line directed by varDir if(ExtremeColors(neighbors, varDir, maxColorPos, minColorPos)) { Vector3D ca = neighbors(minColorPos.x, minColorPos.y); Vector3D cb = neighbors(maxColorPos.x, maxColorPos.y); Vector3D cacb = cb - ca; Vector3D d; alpha = (pixel - ca).dot(cacb) / cacb.dot(cacb); d = pixel - (alpha * cacb) - ca; dp = d.length(); Gd = GAUSS(dp, SIGMA_D); } float eo = Sobel(neighbors); float ef = Sobel(neighborsAliased); ep = ef * eo; Ge = GAUSS(ep, SIGMA_E); Vector3D cbAliased = neighborsAliased(maxColorPos.x, maxColorPos.y); Vector3D caAliased = neighborsAliased(minColorPos.x, minColorPos.y); beta = Gd * (1- Ge); // final composition recovered(i,j) = beta * (caAliased * (1-alpha) + cbAliased * alpha) + (1-beta) * pixelAlias; maxVarDir(i,j) = varDir * 255; sobel(i,j) = Vector3D(sqrt(eo)); } } loader.savePPM(maxVarDir, "max_variance_direction"); loader.savePPM(sobel, "sobel"); return recovered; }
void flowField(Field &field, ofImage &edges, ofPixels pix) { desaturate(pix); blur(pix); sobel(field, edges, pix); }
static void run (gchar *name, gint nparams, GParam *param, gint *nreturn_vals, GParam **return_vals) { static GParam values[1]; TileDrawable *drawable; GRunModeType run_mode; GStatusType status = STATUS_SUCCESS; run_mode = param[0].data.d_int32; INIT_I18N_UI(); *nreturn_vals = 1; *return_vals = values; values[0].type = PARAM_STATUS; values[0].data.d_status = status; switch (run_mode) { case RUN_INTERACTIVE: /* Possibly retrieve data */ gimp_get_data ("plug_in_sobel", &bvals); /* First acquire information with a dialog */ if (! sobel_dialog ()) return; break; case RUN_NONINTERACTIVE: /* Make sure all the arguments are there! */ if (nparams != 6) status = STATUS_CALLING_ERROR; if (status == STATUS_SUCCESS) { bvals.horizontal = (param[4].data.d_int32) ? TRUE : FALSE; bvals.vertical = (param[5].data.d_int32) ? TRUE : FALSE; bvals.keep_sign = (param[6].data.d_int32) ? TRUE : FALSE; } break; case RUN_WITH_LAST_VALS: /* Possibly retrieve data */ gimp_get_data ("plug_in_sobel", &bvals); break; default: break; } /* Get the specified drawable */ drawable = gimp_drawable_get (param[2].data.d_drawable); /* Make sure that the drawable is gray or RGB color */ if (gimp_drawable_color (drawable->id) || gimp_drawable_gray (drawable->id)) { gimp_tile_cache_ntiles (2 * (drawable->width / gimp_tile_width () + 1)); sobel (drawable, bvals.horizontal, bvals.vertical, bvals.keep_sign); if (run_mode != RUN_NONINTERACTIVE) gimp_displays_flush (); /* Store data */ if (run_mode == RUN_INTERACTIVE) gimp_set_data ("plug_in_sobel", &bvals, sizeof (bvals)); } else { /* gimp_message ("sobel: cannot operate on indexed color images"); */ status = STATUS_EXECUTION_ERROR; } gimp_drawable_detach (drawable); values[0].data.d_status = status; }
/* * Apply sobel operator. */ static int sobel(const GP_Context *src, GP_Context *dx, GP_Context *dy, GP_ProgressCallback *callback) { float dx_kern[] = { -1, 0, 1, -2, 0, 2, -1, 0, 1, }; GP_ConvolutionParams dx_conv = { .src = src, .x_src = 0, .y_src = 0, .w_src = src->w, .h_src = src->h, .dst = dx, .x_dst = 0, .y_dst = 0, .kernel = dx_kern, .kw = 3, .kh = 3, .kern_div = 1, .callback = callback, }; if (GP_FilterConvolution_Raw(&dx_conv)) return 1; float dy_kern[] = { -1, -2, -1, 0, 0, 0, 1, 2, 1, }; GP_ConvolutionParams dy_conv = { .src = src, .x_src = 0, .y_src = 0, .w_src = src->w, .h_src = src->h, .dst = dy, .x_dst = 0, .y_dst = 0, .kernel = dy_kern, .kw = 3, .kh = 3, .kern_div = 1, .callback = callback, }; if (GP_FilterConvolution_Raw(&dy_conv)) return 1; return 0; } static int edge_detect(const GP_Context *src, GP_Context **E, GP_Context **Phi, int type, GP_ProgressCallback *callback) { //TODO GP_ASSERT(src->pixel_type == GP_PIXEL_RGB888); GP_Context *dx, *dy; dx = GP_ContextCopy(src, 0); dy = GP_ContextCopy(src, 0); if (dx == NULL || dy == NULL) goto err0; switch (type) { case 0: if (sobel(src, dx, dy, callback)) goto err0; break; case 1: if (prewitt(src, dx, dy, callback)) goto err0; break; default: goto err0; } uint32_t i, j; for (i = 0; i < src->w; i++) { for (j = 0; j < src->h; j++) { GP_Pixel pix_x = GP_GetPixel_Raw_24BPP(dx, i, j); GP_Pixel pix_y = GP_GetPixel_Raw_24BPP(dy, i, j); int Rx, Gx, Bx; int Ry, Gy, By; int RE, GE, BE; int RPhi, GPhi, BPhi; Rx = GP_Pixel_GET_R_RGB888(pix_x); Gx = GP_Pixel_GET_G_RGB888(pix_x); Bx = GP_Pixel_GET_B_RGB888(pix_x); Ry = GP_Pixel_GET_R_RGB888(pix_y); Gy = GP_Pixel_GET_G_RGB888(pix_y); By = GP_Pixel_GET_B_RGB888(pix_y); RE = sqrt(Rx*Rx + Ry*Ry) + 0.5; GE = sqrt(Gx*Gx + Gy*Gy) + 0.5; BE = sqrt(Bx*Bx + By*By) + 0.5; GP_PutPixel_Raw_24BPP(dx, i, j, GP_Pixel_CREATE_RGB888(RE, GE, BE)); if (Rx != 0 && Ry != 0) RPhi = ((atan2(Rx, Ry) + M_PI) * 255)/(2*M_PI); else RPhi = 0; if (Gx != 0 && Gy != 0) GPhi = ((atan2(Gx, Gy) + M_PI) * 255)/(2*M_PI); else GPhi = 0; if (Bx != 0 && By != 0) BPhi = ((atan2(Bx, By) + M_PI) * 255)/(2*M_PI); else BPhi = 0; GP_PutPixel_Raw_24BPP(dy, i, j, GP_Pixel_CREATE_RGB888(RPhi, GPhi, BPhi)); } } if (Phi != NULL) *Phi = dy; else GP_ContextFree(dy); if (E != NULL) *E = dx; else GP_ContextFree(dx); return 0; err0: GP_ContextFree(dx); GP_ContextFree(dy); return 1; } int GP_FilterEdgeSobel(const GP_Context *src, GP_Context **E, GP_Context **Phi, GP_ProgressCallback *callback) { GP_DEBUG(1, "Sobel edge detection image %ux%u", src->w, src->h); return edge_detect(src, E, Phi, 0, callback); }
void HttpHandler::handle_sobel(const char *method, const char *path, const http_options *options, int fd) { media_stream * stream; ssize_t ret_value = 1; const char * my_tmp_option; char my_media_props[100]; int skipframes = 0; int sleeptime = 0; /* handle test stuff */ my_tmp_option = net_http_option(options, "skipframes"); if (my_tmp_option) { skipframes = atoi(my_tmp_option); LOG("%s/%s() skipframes=%d\n", __FILE__, __FUNCTION__, skipframes); } my_tmp_option = net_http_option(options, "sleeptime"); if (my_tmp_option) { sleeptime = atoi(my_tmp_option); LOG("%s/%s() sleeptime=%d\n", __FILE__, __FUNCTION__, sleeptime); } /* handle fps */ my_tmp_option = net_http_option(options, "fps"); if (!my_tmp_option) { my_tmp_option = "10"; } snprintf(my_media_props, sizeof(my_media_props), "fps=%s", my_tmp_option); /* Handle resolution */ my_tmp_option = net_http_option(options, "resolution"); if (my_tmp_option) { strncat(my_media_props, "&resolution=", sizeof(my_media_props) - 1); strncat(my_media_props, my_tmp_option, sizeof(my_media_props) - 1); } else { strncat(my_media_props, "&resolution=352x288", sizeof(my_media_props) - 1); } /* put in the format */ strncat(my_media_props, "&sdk_format=Y800", sizeof(my_media_props) - 1); /* media_props completed */ LOG("%s media_props=\"%s\"\n", __FUNCTION__, my_media_props); stream = capture_open_stream(IMAGE_UNCOMPRESSED, my_media_props); LOG("%s opening stream=%p\n", __FUNCTION__, stream); if (stream) { media_frame *frame = NULL; ret_value = net_http_send_headers(fd, HTTP_TIMEOUT, txt_HTTP_HEADER_200, "Content-Type: image/x-portable-graymap\r\n", txt_CRLF, NULL); if (ret_value < 0) { goto closefd; } /* Read a new buffer */ frame = capture_get_frame(stream); // /* Skip frames, just to stress the system */ // while (skipframes && frame) { // capture_frame_free(frame); // LOG("%s skipframe\n", // __FUNCTION__); // // sleep(sleeptime); // frame = capture_get_frame(stream); // skipframes--; // } /* If buf == NULL: nothing could be read */ /* This could happen if we are using non-blocking read, * or in case of an error. As we are not using non-blocking, * treat it as an error */ if (!frame) { ret_value = -1; LOG("%s/%s frame = NULL\n", __FILE__, __FUNCTION__); goto closefd; } { /* set up an image header first */ int image_height = capture_frame_height(frame); int image_width = capture_frame_width(frame); int image_stride = capture_frame_stride(frame); uint8_t *data = (uint8_t*)capture_frame_data(frame); uint8_t *sobel_data = NULL; const size_t image_header_length = 100; char * my_image_header = NULL; size_t content_length = image_stride * image_height * 4; my_image_header = (char *) malloc(image_header_length + content_length); sobel_data = (uint8_t*)malloc(image_stride * image_height); int pos = 0; if (!my_image_header) { goto closefd; } // ret_value = snprintf(my_image_header, image_header_length, // "P5\n" // "# CREATOR: Axis Communications AB\n" // "%d %d\n" // "%d\n" // "EOH", // image_width, image_height, 255); /* if (ret_value > 0) */{ unsigned char *image = (unsigned char *)(my_image_header); int j; int i; sobel(data, image_width, image_height, image_stride, sobel_data); for (i = 0; i < image_height; i++) { for (j = 0; j < image_width; j++) { pos += sprintf(my_image_header + pos, "%d;", sobel_data[i * image_stride+ j]); } } content_length += ret_value; (void)net_http_send_string_utf8(fd, HTTP_TIMEOUT, my_image_header); } free(my_image_header); free(sobel_data); capture_frame_free(frame); } LOG("%s closing stream=%p", __FUNCTION__, stream); capture_close_stream(stream); } else { net_http_send_headers(fd, HTTP_TIMEOUT, txt_HTTP_RESPONSE_500, txt_CRLF, NULL); } closefd: close(fd); }