Ejemplo n.º 1
0
/******************* TO DO 5 *********************
 * NormalizeBlend:
 *	INPUT:
 *		acc: input image whose alpha channel (4th channel) contains
 *		     normalizing weight values
 *		img: where output image will be stored
 *	OUTPUT:
 *		normalize r,g,b values (first 3 channels) of acc and store it into img
 */
static void NormalizeBlend(CFloatImage& acc, CByteImage& img)
{
	// *** BEGIN TODO ***
	// fill in this routine..
	
	int width = acc.Shape().width;
    int height = acc.Shape().height;
    for (int i=0;i<width;i++){
        for (int j=0;j<height;j++){
            float w = acc.Pixel(i,j,3);
            img.Pixel(i,j,3) = 255;
            if (w > 0){
                img.Pixel(i,j,0) = acc.Pixel(i,j,0) / w;
                img.Pixel(i,j,1) = acc.Pixel(i,j,1) / w;
                img.Pixel(i,j,2) = acc.Pixel(i,j,2) / w;
            } else {
                img.Pixel(i,j,0) = 0;
                img.Pixel(i,j,1) = 0;
                img.Pixel(i,j,2) = 0;
            }
        }
    }


	// *** END TODO ***
}
Ejemplo n.º 2
0
// Compute silly example features.  This doesn't do anything
// meaningful, but may be useful to use as an example.
void dummyComputeFeatures(CFloatImage &image, FeatureSet &features) {
    CShape sh = image.Shape();
    Feature f;

    for (int y=0; y<sh.height; y++) {
        for (int x=0; x<sh.width; x++) {
            double r = image.Pixel(x,y,0);
            double g = image.Pixel(x,y,1);
            double b = image.Pixel(x,y,2);

            if ((int)(255*(r+g+b)+0.5) % 100 == 1) {
                // If the pixel satisfies this meaningless criterion,
                // make it a feature.

                f.type = 1;
                f.id += 1;
                f.x = x;
                f.y = y;

                f.data.resize(1);
                f.data[0] = r + g + b;

                features.push_back(f);
            }
        }
    }
}
Ejemplo n.º 3
0
/******************* TO DO 5 *********************
* NormalizeBlend:
*	INPUT:
*		acc: input image whose alpha channel (4th channel) contains
*		     normalizing weight values
*		img: where output image will be stored
*	OUTPUT:
*		normalize r,g,b values (first 3 channels) of acc and store it into img
*/
static void NormalizeBlend(CFloatImage& acc, CByteImage& img)
{
    // BEGIN TODO
    // fill in this routine..
	// divide the total weight for every pixel
	CShape shacc=acc.Shape();
    int widthacc=shacc.width;
    int heightacc=shacc.height;
	for (int ii=0;ii<widthacc;ii++)
	{
        for (int jj=0;jj<heightacc;jj++)
		{
			if (acc.Pixel(ii,jj,3)>0)
			{
				img.Pixel(ii,jj,0)=(int)(acc.Pixel(ii,jj,0)/acc.Pixel(ii,jj,3));
				img.Pixel(ii,jj,1)=(int)(acc.Pixel(ii,jj,1)/acc.Pixel(ii,jj,3));
				img.Pixel(ii,jj,2)=(int)(acc.Pixel(ii,jj,2)/acc.Pixel(ii,jj,3));
			}
			else
			{
				img.Pixel(ii,jj,0)=0;
				img.Pixel(ii,jj,1)=0;
				img.Pixel(ii,jj,2)=0;
			}
		}
	}

    // END TODO
}
Ejemplo n.º 4
0
void Convolve(CImageOf<T> src, CImageOf<T>& dst,
              CFloatImage kernel)
{
    // Determine the shape of the kernel and source image
    CShape kShape = kernel.Shape();
    CShape sShape = src.Shape();

    // Allocate the result, if necessary
    dst.ReAllocate(sShape, false);
    if (sShape.width * sShape.height * sShape.nBands == 0)
        return;

    // Do the convolution
    for (int y = 0; y < sShape.height; y++)
		for (int x = 0; x < sShape.width; x++)
			for (int c = 0; c < sShape.nBands; c++)
			{
				double sum = 0;
				double sumker = 0;
				for (int k = 0; k < kShape.height; k++)
					for (int l = 0; l < kShape.width; l++)
						if ((x-kernel.origin[0]+k >= 0) && (x-kernel.origin[0]+k < sShape.width) && (y-kernel.origin[1]+l >= 0) && (y-kernel.origin[1]+l < sShape.height))
						{
							sumker += kernel.Pixel(k,l,0);
							sum += kernel.Pixel(k,l,0) * src.Pixel(x-kernel.origin[0]+k,y-kernel.origin[1]+l,c);
						}
				dst.Pixel(x,y,c) = (T) __max(dst.MinVal(), __min(dst.MaxVal(), sum/sumker));
			}
}
Ejemplo n.º 5
0
static
void ConvolveRow2D(CFloatImage& buffer, CFloatImage& kernel, float dst[],
                   int n)
{
    CShape kShape = kernel.Shape();
    int kX  = kShape.width;
    int kY  = kShape.height;
    CShape bShape = buffer.Shape();
    int nB  = bShape.nBands;

    for (int i = 0; i < n; i++)
    {
        for (int b = 0; b < nB; b++)
        {
            float sum = 0.0f;
            for (int k = 0; k < kY; k++)
            {
                float* kPtr = &kernel.Pixel(0, k, 0);
                float* bPtr = &buffer.Pixel(i, k, b);
                for (int l = 0; l < kX; l++, bPtr += nB)
                    sum += kPtr[l] * bPtr[0];
            }
            *dst++ = sum;
        }
    }
}
Ejemplo n.º 6
0
void MotionToColor(CFloatImage motim, CByteImage &colim, float maxmotion)
{
    CShape sh = motim.Shape();
    int width = sh.width, height = sh.height;
    colim.ReAllocate(CShape(width, height, 3));
    int x, y;
    // determine motion range:
    float maxx = -999, maxy = -999;
    float minx =  999, miny =  999;
    float maxrad = -1;
    for (y = 0; y < height; y++) {
	for (x = 0; x < width; x++) {
	    float fx = motim.Pixel(x, y, 0);
	    float fy = motim.Pixel(x, y, 1);
	    if (unknown_flow(fx, fy))
		continue;
	    maxx = __max(maxx, fx);
	    maxy = __max(maxy, fy);
	    minx = __min(minx, fx);
	    miny = __min(miny, fy);
	    float rad = sqrt(fx * fx + fy * fy);
	    maxrad = __max(maxrad, rad);
	}
    }
    printf("max motion: %.4f  motion range: u = %.3f .. %.3f;  v = %.3f .. %.3f\n",
	   maxrad, minx, maxx, miny, maxy);


    if (maxmotion > 0) // i.e., specified on commandline
	maxrad = maxmotion;

    if (maxrad == 0) // if flow == 0 everywhere
	maxrad = 1;

    if (verbose)
	fprintf(stderr, "normalizing by %g\n", maxrad);

    for (y = 0; y < height; y++) {
	for (x = 0; x < width; x++) {
	    float fx = motim.Pixel(x, y, 0);
	    float fy = motim.Pixel(x, y, 1);
	    uchar *pix = &colim.Pixel(x, y, 0);
	    if (unknown_flow(fx, fy)) {
		pix[0] = pix[1] = pix[2] = 0;
	    } else {
		computeColor(fx/maxrad, fy/maxrad, pix);
	    }
	}
    }
}
//TO DO---------------------------------------------------------------------
//Loop through the image to compute the harris corner values as described in class
// srcImage:  grayscale of original image
// harrisImage:  populate the harris values per pixel in this image
void computeHarrisValues(CFloatImage &srcImage, CFloatImage &harrisImage)
{
	int h = srcImage.Shape().height;
	int w = srcImage.Shape().width;

	CFloatImage A(srcImage.Shape());
	CFloatImage B(srcImage.Shape());
	CFloatImage C(srcImage.Shape());

	GetHarrisComponents(srcImage, A, B, C);

    for (int y = 0; y < h; y++) {
        for (int x = 0; x < w; x++) {
			double determinant = A.Pixel(x, y, 0) * C.Pixel(x, y, 0) - B.Pixel(x, y, 0)* B.Pixel(x, y, 0);
			double trace = A.Pixel(x, y, 0) + C.Pixel(x, y, 0);
			
			float *pixel = &harrisImage.Pixel(x, y, 0);

			if (trace == 0)
			{
				*pixel = 0;
			}
			else
			{
				*pixel = determinant / trace;
			}
        }
    }
}
Ejemplo n.º 8
0
void ConvolveRow(CImageOf<T> buffer, CFloatImage kernel, T* dst,
                 int n, T minVal, T maxVal)
{
    CShape kShape = kernel.Shape();
    int kX  = kShape.width;
    int kY  = kShape.height;
    CShape bShape = buffer.Shape();
    int nB  = bShape.nBands;

    for (int i = 0; i < n; i++)
    {
        for (int b = 0; b < nB; b++)
        {
            float sum = 0.0f;
            for (int k = 0; k < kY; k++)
            {
                float* kPtr = &kernel.Pixel(0, k, 0);
                T*     bPtr = &buffer.Pixel(i, k, b);
                for (int l = 0; l < kX; l++, bPtr += nB)
                    sum += kPtr[l] * bPtr[0];
            }
            *dst++ = (T) __max(minVal, __min(maxVal, sum));
        }
    }
}
Ejemplo n.º 9
0
void convertToFloatImage(CByteImage &byteImage, CFloatImage &floatImage) {
	CShape sh = byteImage.Shape();
	//printf("%d\n", floatImage.Shape().nBands);
	//printf("%d\n", byteImage.Shape().nBands);

    assert(floatImage.Shape().nBands == min(byteImage.Shape().nBands, 3));
	for (int y=0; y<sh.height; y++) {
		for (int x=0; x<sh.width; x++) {
			for (int c=0; c<min(3,sh.nBands); c++) {
				float value = byteImage.Pixel(x,y,c) / 255.0f;

				if (value < floatImage.MinVal()) {
					value = floatImage.MinVal();
				}
				else if (value > floatImage.MaxVal()) {
					value = floatImage.MaxVal();
				}

				// We have to flip the image and reverse the color
				// channels to get it to come out right.  How silly!
				floatImage.Pixel(x,sh.height-y-1,min(3,sh.nBands)-c-1) = value;
			}
		}
	}
}
Ejemplo n.º 10
0
void rotation()
{	
		CFloatImage matrixImage = GetImageFromMatrix((float *)featureMatrix, 10, 10);
		CTransform3x3 translationNegative;
		CTransform3x3 translationPositive;
		CTransform3x3 rotation;
		CFloatImage postHomography;

		Feature f;
		f.x = 6;
		f.y = 5;
		f.angleRadians = PI;

		translationNegative = translationNegative.Translation(f.x,f.y);
		translationPositive = translationPositive.Translation(-f.x,-f.y);

		rotation = rotation.Rotation(-f.angleRadians * 180/ PI);


		WarpGlobal(matrixImage, postHomography, translationNegative*rotation*translationPositive, eWarpInterpLinear, eWarpInterpNearest);
		for (int i = 0; i < postHomography.Shape().height; i++)
		{
			for (int j = 0; j < postHomography.Shape().width; j++)
			{
				printf("%.0f\t", postHomography.Pixel(j, i, 0));
			}
			printf("\n");
		}
}
Ejemplo n.º 11
0
// convert float disparity image into a color image using jet colormap
void float2color(CFloatImage fimg, CByteImage &img, float dmin, float dmax)
{
    CShape sh = fimg.Shape();
    int width = sh.width, height = sh.height;
    sh.nBands = 3;
    img.ReAllocate(sh);

    float scale = 1.0 / (dmax - dmin);

    for (int y = 0; y < height; y++) {
	for (int x = 0; x < width; x++) {
	    float f = fimg.Pixel(x, y, 0);
	    int r = 0;
	    int g = 0;
	    int b = 0;
	    
	    if (f != INFINITY) {
		float val = scale * (f - dmin);
		jet(val, r, g, b);
	    }

	    img.Pixel(x, y, 0) = b;
	    img.Pixel(x, y, 1) = g;
	    img.Pixel(x, y, 2) = r;
	}
    }
}
Ejemplo n.º 12
0
void GetHarrisComponents(CFloatImage &srcImage, CFloatImage &A, CFloatImage &B, CFloatImage &C, CFloatImage *partialX, CFloatImage *partialY)
{
	int w = srcImage.Shape().width;
    int h = srcImage.Shape().height;

	CFloatImage *partialXPtr;
	CFloatImage *partialYPtr;

	if (partialX != nullptr && partialY != nullptr)
	{
		partialXPtr = partialX;
		partialYPtr = partialY;
	}
	else
	{
		partialXPtr = new CFloatImage(srcImage.Shape());
		partialYPtr = new CFloatImage(srcImage.Shape());
	}

	CFloatImage partialXX(srcImage.Shape());
	CFloatImage partialYY(srcImage.Shape());
	CFloatImage partialXY(srcImage.Shape());

	CFloatImage gaussianImage = GetImageFromMatrix((float *)gaussian5x5Float, 5, 5);

	Convolve(srcImage, *partialXPtr, ConvolveKernel_SobelX);
	Convolve(srcImage, *partialYPtr, ConvolveKernel_SobelY);
	
	for (int y = 0; y < h; y++) {
        for (int x = 0; x < w; x++) {
			float *xxPixel = &partialXX.Pixel(x, y, 0);
			float *yyPixel = &partialYY.Pixel(x, y, 0);
			float *xyPixel = &partialXY.Pixel(x, y, 0);
			
			// The 1/8 factor is to do the scaling inherent in sobel filtering
			*xxPixel = pow((double)(1./8. *8. * partialXPtr->Pixel(x, y, 0)), 2.);
			*yyPixel = pow((double)(1./8. *8. * partialYPtr->Pixel(x, y, 0)), 2.);
			*xyPixel = pow(1./8. *8., 2.) * partialXPtr->Pixel(x, y, 0) * partialYPtr->Pixel(x, y, 0);
		}
	}

	Convolve(partialXX, A, gaussianImage);
	Convolve(partialXY, B, gaussianImage);
	Convolve(partialYY, C, gaussianImage);
}
Ejemplo n.º 13
0
// TO DO---------------------------------------------------------------------
// Loop through the harrisImage to threshold and compute the local maxima in a neighborhood
// srcImage:  image with Harris values
// destImage: Assign 1 to a pixel if it is above a threshold and is the local maximum in 3x3 window, 0 otherwise.
//    You'll need to find a good threshold to use.
void computeLocalMaxima(CFloatImage &srcImage,CByteImage &destImage)
{
	int width = srcImage.Shape().width;
	int height = srcImage.Shape().height;

	double mean, stdDev;
	double sum = 0;
	double squareSum = 0;

	for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
			float pixel = srcImage.Pixel(x, y, 0);
			if (!(pixel >= 0 || pixel < 0))
			{
				auto error = "TRUE";
			}
			sum += srcImage.Pixel(x, y, 0);
		}
    }

	mean = sum / (float)(width * height);

	for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            squareSum += pow((srcImage.Pixel(x, y, 0) - mean), 2.);
        }
    }

	stdDev = sqrt(squareSum / (float)(width * height - 1));
	int count = 0;
	for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
			unsigned char *pixel = &destImage.Pixel(x, y, 0);
			if (srcImage.Pixel(x, y, 0) >= 3.*stdDev + mean && isLocalMax(srcImage, x, y))
			{
				count++;
				*pixel = 1;
			}
			else
			{
				*pixel = 0;
			}
        }
    }
}
Ejemplo n.º 14
0
//Loop through the image to determine suitable feature points
// srcImage:  image with Harris values
// destImage: Assign 1 to local maximum in 3x3 window that are above a given 
//            threshold, 0 otherwise
void computeLocalMaxima(CFloatImage &srcImage,CByteImage &destImage)
{
	int w = srcImage.Shape().width;	 // image width
	int h = srcImage.Shape().height; // image height
	
	//float threshold = .024;
	float threshold = .01;	// threshold value for identifying features


	// Declare additional variables
	float max;		// harris value to check as local max
	int newX, newY;	// (x,y) coordinate for pixel in 5x5 sliding window 
	int j;			// int for iterating through 5x5 window

	// Loop through 'srcImage' and determine suitable feature points that
	// fit the following criteria:
	//   - harris value c is greater than a predefined threshold
	//   - c is a local maximum in a 5x5 neighborhood
	for (int y = 0; y < h; y++) {
		for (int x = 0; x < w; x++) {

			max = srcImage.Pixel(x,y,0);
			
			// If harris value is greater than a predefined threshold check
			// if value is a local maximum in a 5x5 neighborhood.
			if (max > threshold) {
				for (j = 0; j < 25; j++) {
					find5x5Index(x,y,j,&newX,&newY);
					if(srcImage.Shape().InBounds(newX, newY) && srcImage.Pixel(newX, newY, 0) > max) {
						destImage.Pixel(x,y,0) = 0;
						break;
					}
				}
				if (j != 25) 
					continue;
				destImage.Pixel(x,y,0) = 1;
			} else {
				destImage.Pixel(x,y,0) = 0;
			}
		}
	}
}
Ejemplo n.º 15
0
// Convert Fl_Image to CFloatImage.
bool convertImage(const Fl_Image *image, CFloatImage &convertedImage) {
    if (image == NULL) {
        return false;
    }

    // Let's not handle indexed color images.
    if (image->count() != 1) {
        return false;
    }

    int w = image->w();
    int h = image->h();
    int d = image->d();

    // Get the image data.
    const char *const *data = image->data();

    int index = 0;

    for (int y=0; y<h; y++) {
        for (int x=0; x<w; x++) {
            if (d < 3) {
		// If there are fewer than 3 channels, just use the
		// first one for all colors.
		convertedImage.Pixel(x,y,0) = ((uchar) data[0][index]) / 255.0f;
		convertedImage.Pixel(x,y,1) = ((uchar) data[0][index]) / 255.0f;
		convertedImage.Pixel(x,y,2) = ((uchar) data[0][index]) / 255.0f;
            }
            else {
		// Otherwise, use the first 3.
		convertedImage.Pixel(x,y,0) = ((uchar) data[0][index]) / 255.0f;
		convertedImage.Pixel(x,y,1) = ((uchar) data[0][index+1]) / 255.0f;
		convertedImage.Pixel(x,y,2) = ((uchar) data[0][index+2]) / 255.0f;
            }

            index += d;
        }
    }
        
    return true;
}
Ejemplo n.º 16
0
void featuresFromImage(Feature* f, CFloatImage img, int width, int height)
{
	vector<double, std::allocator<double>>::iterator it;
	f->data.clear();
	for(int y=0; y<height; y++)
	{
		for(int x=0; x<width; x++)
		{
			f->data.push_back(img.Pixel(x,y,0));
		}
	}
}
Ejemplo n.º 17
0
double GetCanonicalOrientation(int x, int y, CFloatImage A, CFloatImage B, CFloatImage C, CFloatImage partialX, CFloatImage partialY)
{
	float aPixel = A.Pixel(x, y, 0);	
	float bPixel = B.Pixel(x, y, 0);	
	float cPixel = C.Pixel(x, y, 0);	

	/*double a = 1;
	double b = -(aPixel+cPixel);
	double c = (aPixel * cPixel - pow((double)bPixel, 2.));*/

	//double lambda = (- b + sqrt(pow((double)b, 2.) - 4.*a*c)) / (2.*a);

	double lambda = 1./2. *((aPixel+cPixel) + sqrt(4.*pow((double)bPixel,2.) + pow(((double)aPixel - cPixel), 2.)));
	double yComponent = aPixel - lambda - bPixel;
	double xComponent = cPixel - lambda - bPixel;
	/*y = -b
	x = a - lambd
	*/
	if (xComponent == 0.)
	{
		return (partialY.Pixel(x, y, 0) > 0)? PI/2. : -PI/2.;
	}

	double first = aPixel*xComponent + bPixel*yComponent;
	double second = bPixel*xComponent + cPixel*yComponent;
	double first_precision = pow((first -lambda * xComponent), 2.);
	double second_precision = pow((second - lambda * yComponent), 2.);

	//Sanity check for eigenvalues: this confirms our given eigenvalue is
	//computed correctly
	if (first_precision > .0000001 || second_precision > .0000001 )
	{
		int z = 3;
	}

	return (partialX.Pixel(x, y, 0) > 0)? atan(-bPixel/(aPixel-lambda)) : atan(-bPixel/(aPixel-lambda)) + PI;

	//return (partialX.Pixel(x, y, 0) > 0)? atan(yComponent/xComponent) : atan(yComponent/xComponent) + PI;
}
Ejemplo n.º 18
0
void makeNonoccMask(CFloatImage disp0, CFloatImage disp0y, CFloatImage disp1,
		    int dir, float thresh, CByteImage &mask)
{
    CShape sh = disp0.Shape();
    int width = sh.width, height = sh.height;

    if (sh != disp1.Shape())
	throw CError("shapes differ");

    int ydisps = (sh == disp0y.Shape());

    mask.ReAllocate(sh);
    mask.ClearPixels();
    int x, y;
    for (y = 0; y < height; y++) {
	for (x = 0; x < width; x++) {
	    float dx = disp0.Pixel(x, y, 0);
	    float dy = (ydisps ? disp0y.Pixel(x, y, 0) : 0.0);
	    if (dx == INFINITY) // unknown
		continue;
	    mask.Pixel(x, y, 0) = 128; // occluded

	    // find nonocc
	    int x1 = (int)round(x + dir * dx);
	    int y1 = (int)round(y + dy);
	    if (x1 < 0 || x1 >= width || y1 < 0 || y1 >= height)
		continue;
	    float dx1 = disp1.Pixel(x1, y1, 0);

	    float diff = dx - dx1;
	    if (fabs(diff) > thresh)
		continue; // fails cross checking -- occluded

	    mask.Pixel(x, y, 0) = 255; // cross-checking OK
	}
    }
}
Ejemplo n.º 19
0
bool isLocalMax(CFloatImage srcImage, int x, int y)
{
	int width = srcImage.Shape().width;
	int height = srcImage.Shape().height;
	float centerPixel = srcImage.Pixel(x, y, 0);

	for (int row = 0; row < 5; row++)
	{
		for (int col = 0; col < 5; col++)
		{
			int xOffset = x - 2 + col;
			int yOffset = y - 2 + row;

			if (xOffset == x && yOffset == y)
			{
				continue;
			}

			float pixelAtOffset;
			if (xOffset < 0 || yOffset < 0 || xOffset >= width || yOffset >= height)
			{
				pixelAtOffset = 0.;
			}
			else
			{
				pixelAtOffset = srcImage.Pixel(xOffset, yOffset, 0);
			}
			if (pixelAtOffset >= centerPixel)
			{
				return false;
			}
		}
	}

	return true;
}
Ejemplo n.º 20
0
void ConvolveSeparable(CImageOf<T> src, CImageOf<T>& dst,
                       CFloatImage x_kernel, CFloatImage y_kernel,
                       float scale, float offset,
                       int decimate, int interpolate)
{
    // Allocate the result, if necessary
    CShape dShape = src.Shape();
    if (decimate > 1)
    {
        dShape.width  = (dShape.width  + decimate-1) / decimate;
        dShape.height = (dShape.height + decimate-1) / decimate;
    }
    dst.ReAllocate(dShape, false);

    // Allocate the intermediate images
    CImageOf<T> tmpImg1(src.Shape());
    CImageOf<T> tmpImg2(src.Shape());

    // Create a proper vertical convolution kernel
    CFloatImage v_kernel(1, y_kernel.Shape().width, 1);
    for (int k = 0; k < y_kernel.Shape().width; k++)
        v_kernel.Pixel(0, k, 0) = y_kernel.Pixel(k, 0, 0);
    v_kernel.origin[1] = y_kernel.origin[0];

    // Perform the two convolutions
    Convolve(src, tmpImg1, x_kernel, 1.0f, 0.0f);
    Convolve(tmpImg1, tmpImg2, v_kernel, scale, offset);

    // Downsample or copy
    for (int y = 0; y < dShape.height; y++)
    {
        T* sPtr = &tmpImg2.Pixel(0, y * decimate, 0);
        T* dPtr = &dst.Pixel(0, y, 0);
        int nB  = dShape.nBands;
        for (int x = 0; x < dShape.width; x++)
        {
            for (int b = 0; b < nB; b++)
                dPtr[b] = sPtr[b];
            sPtr += decimate * nB;
            dPtr += nB;
        }
    }

    interpolate++; // to get rid of "unused parameter" warning
}
Ejemplo n.º 21
0
// get min and max (non-INF) values
void getMinMax(CFloatImage fimg, float& vmin, float& vmax)
{
    CShape sh = fimg.Shape();
    int width = sh.width, height = sh.height;

    vmin = INFINITY;
    vmax = -INFINITY;

    for (int y = 0; y < height; y++) {
	for (int x = 0; x < width; x++) {
	    float f = fimg.Pixel(x, y, 0);
	    if (f == INFINITY)
		continue;
	    vmin = min(f, vmin);
	    vmax = max(f, vmax);
	}
    }
}
Ejemplo n.º 22
0
void ConvolveSeparable(CImageOf<T> src, CImageOf<T>& dst,
                       CFloatImage x_kernel, CFloatImage y_kernel,
                       int subsample)
{
    // Allocate the result, if necessary
    CShape dShape = src.Shape();
    if (subsample > 1)
    {
        dShape.width  = (dShape.width  + subsample-1) / subsample;
        dShape.height = (dShape.height + subsample-1) / subsample;
    }
    dst.ReAllocate(dShape, false);

    // Allocate the intermediate images
    CImageOf<T> tmpImg1(src.Shape());
    CImageOf<T> tmpImg2(src.Shape());

    // Create a proper vertical convolution kernel
    CFloatImage v_kernel(1, y_kernel.Shape().width, 1);
    for (int k = 0; k < y_kernel.Shape().width; k++)
        v_kernel.Pixel(0, k, 0) = y_kernel.Pixel(k, 0, 0);
    v_kernel.origin[1] = y_kernel.origin[0];

    // Perform the two convolutions
    Convolve(src, tmpImg1, x_kernel);
    Convolve(tmpImg1, tmpImg2, v_kernel);
				
    // Downsample or copy
    for (int y = 0; y < dShape.height; y++)
    {
        T* sPtr = &tmpImg2.Pixel(0, y * subsample, 0);
        T* dPtr = &dst.Pixel(0, y, 0);
        int nB  = dShape.nBands;
        for (int x = 0; x < dShape.width; x++)
        {
            for (int b = 0; b < nB; b++)
                dPtr[b] = sPtr[b];
            sPtr += subsample * nB;
            dPtr += nB;
        }
    }
}
Ejemplo n.º 23
0
CFloatImage GetXWindowAroundPixel(CFloatImage srcImage, int x, int y, int size)
{
	float *matrix = new float[size * size];

	for(int row=(y-(size-1)/2); row<=(y+(size-1)/2); row++)
		{
			for(int col=(x-(size-1)/2);col<=(x+(size-1)/2);col++)
			{
				if(row<0 || row>=srcImage.Shape().height || col<0 || col>=srcImage.Shape().width)
				{
					matrix[(row-(y-(size-1)/2))*size + (col-(x-(size-1)/2))] = 0.;
				}
				else
				{
					matrix[(row-(y-(size-1)/2))*size + (col-(x-(size-1)/2))] = srcImage.Pixel(col, row, 0);
				}
			}
		}
	return GetImageFromMatrix(matrix, size, size);
}
cv::Mat FlowIOOpenCVWrapper::read(std::string path) {
    
    CFloatImage flow;
    ReadFlowFile(flow, path.c_str());
    
    int rows = flow.Shape().height;
    int cols = flow.Shape().width;
    
    assert(rows > 0);
    assert(cols > 0);
    assert(flow.Shape().nBands == 2);
    
    cv::Mat matFlow(rows, cols, CV_32FC2, cv::Scalar(0, 0));
    
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            matFlow.at<cv::Vec2f>(i, j)[0] = flow.Pixel(j, i, 0);
            matFlow.at<cv::Vec2f>(i, j)[1] = flow.Pixel(j, i, 1);
        }
    }
    
    return matFlow;
}
Ejemplo n.º 25
0
// Convert CFloatImage to CByteImage.
void convertToByteImage(CFloatImage &floatImage, CByteImage &byteImage) {
    CShape sh = floatImage.Shape();

    assert(floatImage.Shape().nBands == byteImage.Shape().nBands);
    for (int y=0; y<sh.height; y++) {
        for (int x=0; x<sh.width; x++) {
            for (int c=0; c<sh.nBands; c++) {
		float value = floor(255*floatImage.Pixel(x,y,c) + 0.5f);

		if (value < byteImage.MinVal()) {
                    value = byteImage.MinVal();
		}
		else if (value > byteImage.MaxVal()) {
                    value = byteImage.MaxVal();
		}

		// We have to flip the image and reverse the color
		// channels to get it to come out right.  How silly!
		byteImage.Pixel(x,sh.height-y-1,sh.nBands-c-1) = (uchar) value;
            }
        }
    }
}
void
SupportVectorMachine::predictSlidingWindow(const Feature &feat, CFloatImage &response) const
{
    response.ReAllocate(CShape(feat.Shape().width, feat.Shape().height, 1));
    response.ClearPixels();

    /******** BEGIN TODO ********/
    // Sliding window prediction.
    //
    // In this project we are using a linear SVM. This means that
    // it's classification function is very simple, consisting of a
    // dot product of the feature vector with a set of weights learned
    // during training, followed by a subtraction of a bias term
    //
    //          pred <- dot(feat, weights) - bias term
    //
    // Now this is very simple to compute when we are dealing with
    // cropped images, our computed features have the same dimensions
    // as the SVM weights. Things get a little more tricky when you
    // want to evaluate this function over all possible subwindows of
    // a larger feature, one that we would get by running our feature
    // extraction on an entire image.
    //
    // Here you will evaluate the above expression by breaking
    // the dot product into a series of convolutions (remember that
    // a convolution can be though of as a point wise dot product with
    // the convolution kernel), each one with a different band.
    //
    // Convolve each band of the SVM weights with the corresponding
    // band in feat, and add the resulting score image. The final
    // step is to subtract the SVM bias term given by this->getBiasTerm().
    //
    // Hint: you might need to set the origin for the convolution kernel
    // in order to get the result from convoltion to be correctly centered
    //
    // Useful functions:
    // Convolve, BandSelect, this->getWeights(), this->getBiasTerm()

Feature weights = this->getWeights();
	int nWtBands = weights.Shape().nBands;
	
	// Set the center of the window as the origin for the conv. kernel
	for (int band = 0; band < nWtBands; band++)
	{
		// Select a band
		CFloatImage featBand;
		CFloatImage weightBand;
		BandSelect(feat, featBand, band, 0);
		BandSelect(weights, weightBand, band, 0);

		// Set the origin of the kernel
		weightBand.origin[0] = weights.Shape().width / 2;
		weightBand.origin[1] = weights.Shape().height / 2;
		
		// Compute the dot product
		CFloatImage dotproduct;
		dotproduct.ClearPixels();
		Convolve(featBand, dotproduct, weightBand);

		// Add the resulting score image
		for (int y = 0; y < feat.Shape().height; y++)
		{
			for (int x = 0; x < feat.Shape().width; x++)
			{
				response.Pixel(x, y, 0) += dotproduct.Pixel(x, y, 0);
			}
			// End of x loop
		}
		// End of y loop
	}
	// End of band loop
	
	// Substract the SVM bias term
	for (int y = 0; y < feat.Shape().height; y++)
	{
		for (int x = 0; x < feat.Shape().width; x++)
		{
			response.Pixel(x, y, 0) -= this->getBiasTerm();
		}
		// End of x loop
	}
	// End of y loop

    /******** END TODO ********/
}
Ejemplo n.º 27
0
/******************* TO DO *********************
* AccumulateBlend:
*	INPUT:
*		img: a new image to be added to acc
*		acc: portion of the accumulated image where img is to be added
*       M: the transformation mapping the input image 'img' into the output panorama 'acc'
*		blendWidth: width of the blending function (horizontal hat function;
*	    try other blending functions for extra credit)
*	OUTPUT:
*		add a weighted copy of img to the subimage specified in acc
*		the first 3 band of acc records the weighted sum of pixel colors
*		the fourth band of acc records the sum of weight
*/
static void AccumulateBlend(CByteImage& img, CFloatImage& acc, CTransform3x3 M, float blendWidth)
{
    // BEGIN TODO
    // Fill in this routine
	// get shape of acc and img
	CShape sh = img.Shape();
    int width = sh.width;
    int height = sh.height;
	CShape shacc = acc.Shape();
    int widthacc = shacc.width;
    int heightacc = shacc.height;
	
	// get the bounding box of img in acc
	int min_x, min_y, max_x, max_y;
	ImageBoundingBox(img, M, min_x, min_y, max_x, max_y);

	CVector3 p;
	double newx, newy;

	// Exposure Compensation
	double lumaScale = 1.0;
	double lumaAcc = 0.0;
	double lumaImg = 0.0;
	int cnt = 0;

	for (int ii = min_x; ii < max_x; ii++)
		for (int jj = min_y; jj < max_y; jj++)
		{
			// flag: current pixel black or not
			bool flag = false;
			p[0] = ii; p[1] = jj; p[2] = 1;
			p = M.Inverse() * p;
			newx = p[0] / p[2];
			newy = p[1] / p[2];
			// If in the overlapping region
			if (newx >=0 && newx < width && newy >=0 && newy < height)
			{
				if (acc.Pixel(ii,jj,0) == 0 &&
					acc.Pixel(ii,jj,1) == 0 &&
					acc.Pixel(ii,jj,2) == 0)
					flag = true;
				if (img.PixelLerp(newx,newy,0) == 0 &&
					img.PixelLerp(newx,newy,1) == 0 &&
					img.PixelLerp(newx,newy,2) == 0)
					flag = true;
				if (!flag)
				{
					// Compute Y using RGB (RGB -> YUV)
					lumaAcc = 0.299 * acc.Pixel(ii,jj,0) +
							   0.587 * acc.Pixel(ii,jj,1) +
							   0.114 * acc.Pixel(ii,jj,2);
					lumaImg = 0.299 * img.PixelLerp(newx,newy,0) +
							   0.587 * img.PixelLerp(newx,newy,1) +
							   0.114 * img.PixelLerp(newx,newy,2);
					
					if (lumaImg != 0)
					{
						double scale = lumaAcc / lumaImg;
						if (scale > 0.5 && scale < 2)
						{
							lumaScale += lumaAcc / lumaImg;
							cnt++;
						}
					}
				}
			}
		}

	if (cnt != 0)
		lumaScale = lumaScale / (double)cnt;
	else lumaScale = 1.0;

	// add every pixel in img to acc, feather the region withing blendwidth to the bounding box,
	// pure black pixels (caused by warping) are not added
	double weight;
	
	for (int ii = min_x; ii < max_x; ii++)
		for (int jj = min_y; jj < max_y; jj++)
		{
			p[0] = ii; p[1] = jj; p[2] = 1;
			p = M.Inverse() * p;
			newx = p[0] / p[2];
			newy = p[1] / p[2];
			if ((newx >= 0) && (newx < width-1) && (newy >= 0) && (newy < height-1))
			{
				weight = 1.0;
				if ( (ii >= min_x) && (ii < (min_x+blendWidth)) )
					weight = (ii-min_x) / blendWidth;
				if ( (ii <= max_x) && (ii > (max_x-blendWidth)) )
					weight = (max_x-ii) / blendWidth;
				if (img.Pixel(iround(newx),iround(newy),0) == 0 &&
					img.Pixel(iround(newx),iround(newy),1) == 0 &&
					img.Pixel(iround(newx),iround(newy),2) == 0)
					weight = 0.0;

				double LerpR = img.PixelLerp(newx, newy, 0);
				double LerpG = img.PixelLerp(newx, newy, 1);
				double LerpB = img.PixelLerp(newx, newy, 2);
				
				double r = LerpR*lumaScale > 255.0 ? 255.0 : LerpR*lumaScale;
				double g = LerpG*lumaScale > 255.0 ? 255.0 : LerpG*lumaScale;
				double b = LerpB*lumaScale > 255.0 ? 255.0 : LerpB*lumaScale;
				acc.Pixel(ii,jj,0) += r * weight;
				acc.Pixel(ii,jj,1) += g * weight;
				acc.Pixel(ii,jj,2) += b * weight;
				acc.Pixel(ii,jj,3) += weight;
			}
		}
	
	printf("AccumulateBlend\n"); 

    // END TODO
}
Ejemplo n.º 28
0
void ConvolveSeparable(CImageOf<T> src, CImageOf<T>& dst,
                       CFloatImage x_kernel, CFloatImage y_kernel,
                       float scale, float offset,
                       int decimate, int interpolate)
{
    // Allocate the result, if necessary
    CShape dShape = src.Shape();
    if (decimate > 1)
    {
        dShape.width  = (dShape.width  + decimate-1) / decimate;
        dShape.height = (dShape.height + decimate-1) / decimate;
    }
    dst.ReAllocate(dShape, false);

    // Allocate the intermediate images
    CImageOf<T> tmpImg1(src.Shape());
    //CImageOf<T> tmpImgCUDA(src.Shape());
    CImageOf<T> tmpImg2(src.Shape());

    // Create a proper vertical convolution kernel
    CFloatImage v_kernel(1, y_kernel.Shape().width, 1);
    for (int k = 0; k < y_kernel.Shape().width; k++)
        v_kernel.Pixel(0, k, 0) = y_kernel.Pixel(k, 0, 0);
    v_kernel.origin[1] = y_kernel.origin[0];

#ifdef RUN_ON_GPU
    // Modifications for integrating CUDA kernels
    BinomialFilterType type;

    profilingTimer->startTimer();

    // CUDA Convolve
    switch (x_kernel.Shape().width)
    {
       case 3:
           type = BINOMIAL6126;
           break;
       case 5:
           type = BINOMIAL14641;
           break;
       default:
           // Unsupported kernel case
           throw CError("Convolution kernel Unknown");
           assert(false);
    }

    // Skip copy if decimation is not required
    if (decimate != 1) CudaConvolveXY(src, tmpImg2, type); 
    else CudaConvolveXY(src, dst, type);

    printf("\nGPU convolution time = %f ms\n", profilingTimer->stopAndGetTimerValue());
#else

    profilingTimer->startTimer();
    //VerifyComputedData(&tmpImg2.Pixel(0, 0, 0), &tmpImgCUDA.Pixel(0, 0, 0), 7003904);

    // Perform the two convolutions
    Convolve(src, tmpImg1, x_kernel, 1.0f, 0.0f);
    Convolve(tmpImg1, tmpImg2, v_kernel, scale, offset);

    printf("\nCPU Convolution time = %f ms\n", profilingTimer->stopAndGetTimerValue());
#endif

    profilingTimer->startTimer();
    // Downsample or copy
    // Skip decimate and recopy if not required
#ifdef RUN_ON_GPU
    if (decimate != 1)
    {
#endif
       for (int y = 0; y < dShape.height; y++)
       {
           T* sPtr = &tmpImg2.Pixel(0, y * decimate, 0);
           T* dPtr = &dst.Pixel(0, y, 0);
           int nB  = dShape.nBands;
           for (int x = 0; x < dShape.width; x++)
           {
               for (int b = 0; b < nB; b++)
                   dPtr[b] = sPtr[b];
               sPtr += decimate * nB;
               dPtr += nB;
           }
       }
#ifdef RUN_ON_GPU
    }
#endif
    printf("\nDecimate/Recopy took = %f ms\n", profilingTimer->stopAndGetTimerValue());
}
Ejemplo n.º 29
0
void evaldisp(CFloatImage disp, CFloatImage gtdisp, CByteImage mask, float badthresh, int maxdisp, int rounddisp)
{
    CShape sh = gtdisp.Shape();
    CShape sh2 = disp.Shape();
    CShape msh = mask.Shape();
    int width = sh.width, height = sh.height;
    int width2 = sh2.width, height2 = sh2.height;
    int scale = width / width2;

    if ((!(scale == 1 || scale == 2 || scale == 4))
	|| (scale * width2 != width)
	|| (scale * height2 != height)) {
	printf("   disp size = %4d x %4d\n", width2, height2);
	printf("GT disp size = %4d x %4d\n", width,  height);
	throw CError("GT disp size must be exactly 1, 2, or 4 * disp size");
    }

    int usemask = (msh.width > 0 && msh.height > 0);
    if (usemask && (msh != sh))
	throw CError("mask image must have same size as GT\n");

    int n = 0;
    int bad = 0;
    int invalid = 0;
    float serr = 0;
    for (int y = 0; y < height; y++) {
	for (int x = 0; x < width; x++) {
	    float gt = gtdisp.Pixel(x, y, 0);
	    if (gt == INFINITY) // unknown
		continue;
	    float d = scale * disp.Pixel(x / scale, y / scale, 0);
		float maxd = scale * maxdisp; // max disp range
	    int valid = (d != INFINITY && d <= maxd * 1000);
	    if (valid) {
		d = __max(0, __min(maxd, d)); // clip disps to max disp range
	    }
	    if (valid && rounddisp)
		d = round(d);
	    float err = fabs(d - gt);
	    if (usemask && mask.Pixel(x, y, 0) != 255) { // don't evaluate pixel
	    } else {
		n++;
		if (valid) {
		    serr += err;
		    if (err > badthresh) {
			bad++;
		    }
		} else {// invalid (i.e. hole in sparse disp map)
		    invalid++;
		}
	    }
	}
    }
    float badpercent =  100.0*bad/n;
    float invalidpercent =  100.0*invalid/n;
    float totalbadpercent =  100.0*(bad+invalid)/n;
    float avgErr = serr / (n - invalid); // CHANGED 10/14/2014 -- was: serr / n
    //printf("mask  bad%.1f  invalid  totbad   avgErr\n", badthresh);
    printf("%4.1f  %6.2f  %6.2f   %6.2f  %6.2f\n",   100.0*n/(width * height),
	   badpercent, invalidpercent, totalbadpercent, avgErr);
}
Ejemplo n.º 30
0
/******************* TO DO 4 *********************
 * AccumulateBlend:
 *	INPUT:
 *		img: a new image to be added to acc
 *		acc: portion of the accumulated image where img is to be added
 *		M: translation matrix for calculating a bounding box
 *		blendWidth: width of the blending function (horizontal hat function;
 *	    try other blending functions for extra credit)
 *	OUTPUT:
 *		add a weighted copy of img to the subimage specified in acc
 *		the first 3 band of acc records the weighted sum of pixel colors
 *		the fourth band of acc records the sum of weight
 */
static void AccumulateBlend(CByteImage& img, CFloatImage& acc, CTransform3x3 M, float blendWidth)
{
    /* Compute the bounding box of the image of the image */
    int bb_min_x, bb_min_y, bb_max_x, bb_max_y;
    ImageBoundingBox(img, M, bb_min_x, bb_min_y, bb_max_x, bb_max_y);

	int imgWidth = img.Shape().width;
	int imgHeight = img.Shape().height;

    CTransform3x3 Minv = M.Inverse();

    for (int y = bb_min_y; y <= bb_max_y; y++) {
        for (int x = bb_min_x; x < bb_max_x; x++) {
            /* Check bounds in destination */
            if (x < 0 || x >= acc.Shape().width || 
                y < 0 || y >= acc.Shape().height)
                continue;

            /* Compute source pixel and check bounds in source */
            CVector3 p_dest, p_src;
            p_dest[0] = x;
            p_dest[1] = y;
            p_dest[2] = 1.0;

            p_src = Minv * p_dest;

            float x_src = (float) (p_src[0] / p_src[2]);
            float y_src = (float) (p_src[1] / p_src[2]);

            if (x_src < 0.0 || x_src >= img.Shape().width - 1 ||
                y_src < 0.0 || y_src >= img.Shape().height - 1)
                continue;

            int xf = (int) floor(x_src);
            int yf = (int) floor(y_src);
            int xc = xf + 1;
            int yc = yf + 1;

            /* Skip black pixels */
            if (img.Pixel(xf, yf, 0) == 0x0 && 
                img.Pixel(xf, yf, 1) == 0x0 && 
                img.Pixel(xf, yf, 2) == 0x0)
                continue;

            if (img.Pixel(xc, yf, 0) == 0x0 && 
                img.Pixel(xc, yf, 1) == 0x0 && 
                img.Pixel(xc, yf, 2) == 0x0)
                continue;

            if (img.Pixel(xf, yc, 0) == 0x0 && 
                img.Pixel(xf, yc, 1) == 0x0 && 
                img.Pixel(xf, yc, 2) == 0x0)
                continue;

            if (img.Pixel(xc, yc, 0) == 0x0 && 
                img.Pixel(xc, yc, 1) == 0x0 && 
                img.Pixel(xc, yc, 2) == 0x0)
                continue;

            
            double weight = 1.0;

			// *** BEGIN TODO ***
			// set weight properly
			//(see mosaics lecture slide on "feathering") P455 on notebook
			//Q:How to find the invalid distance ? -> 
	
			double distance = ((imgWidth - x - 1)*(imgWidth - x - 1) + (imgHeight - y - 1)*(imgHeight - y - 1));
			if (distance < blendWidth)
			{
				weight = distance / blendWidth;
			}

            
			// *** END TODO ***	

			acc.Pixel(x, y, 0) += (float) (weight * img.PixelLerp(x_src, y_src, 0));
            acc.Pixel(x, y, 1) += (float) (weight * img.PixelLerp(x_src, y_src, 1));
            acc.Pixel(x, y, 2) += (float) (weight * img.PixelLerp(x_src, y_src, 2));
            acc.Pixel(x, y, 3) += (float) weight;
        }
    }
}