Esempio n. 1
0
bool CObjectView::loadTexture(const char *file,  GLuint *tex){
  //  kill old one
  if (!glIsTexture(*tex)){
    //  load new texture
    glGenTextures(1, tex);
    glBindTexture(GL_TEXTURE_2D, *tex);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, /*GL_LINEAR*/GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, /*GL_LINEAR*/GL_NEAREST);
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
    }
  else{
    glBindTexture(GL_TEXTURE_2D, *tex);
    }

  CProgressMeter pm(this);
  pm.init();

  ImageRGB im;
  char *err;
  float r = im.loadTexture(file, &err, &pm);
  if (r > 0){
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, im.getN(), im.getM(), 0, GL_RGB, GL_UNSIGNED_BYTE, &im.index(0, 0));
    return true;
    }
  else{
    AfxMessageBox(err, MB_OK | MB_ICONSTOP);
    return false;
    }
}
Esempio n. 2
0
	// Minimal mock of VW imageio routines
	void ReadImage(const std::string& file, ImageRGB<byte>& image) {
		CHECK_PRED1(fs::exists, file);
		bool jpeg = IsJpegFilename(file);

		// Get size
		point2<ptrdiff_t> size;
		if (jpeg) {
			size = jpeg_read_dimensions(file);
		} else {
			size = png_read_dimensions(file);
		}

		// Allocate image data
		image.AllocImageData(size.x, size.y);
		rgba8_view_t v = interleaved_view(image.GetWidth(),
																			image.GetHeight(),
																			(rgba8_pixel_t*)image.GetImageBuffer(),
																			image.GetWidth()*sizeof(PixelRGB<byte>));

		// Load the image
		if (jpeg) {
			jpeg_read_and_convert_view(file, v);
		} else {
			png_read_and_convert_view(file, v);
		}

		// GIL uses 255=opaque but we use 0=opaque
		InvertAlpha(image);
	}
Esempio n. 3
0
	void Compute(const ImageRGB<byte>& imagergb,
							 const ImageHSV<byte>& imagehsv,
							 const MatI& seg,
							 int num_segments) {
		const int& w = imagergb.GetWidth();
		const int& h = imagergb.GetHeight();
		// Compute pixel features
		pixel_ftrs.Compute(imagergb, imagehsv);

		// Build histograms over labels for each segment
		hists.Resize(num_segments, pixel_ftrs.label_map.MaxValue()+1);
		hists.Fill(0);
		for (int r = 0; r < h; r++) {
			const int* labelrow = pixel_ftrs.label_map[r];
			const int* segrow = seg[r];
			for (int c = 0; c < w; c++) {
				hists[ segrow[c] ][ labelrow[c] ]++;
			}
		}

		// Normalize the histograms
		features.resize(num_segments);
		for (int i = 0; i < num_segments; i++) {
			features[i] = hists.GetRow(i);
			features[i] /= features[i].Sum();
		}
	}
Esempio n. 4
0
	void Compute(const ImageRGB<byte>& image, const ImageHSV<byte>& imagehsv) {
		const int& w = image.GetWidth();
		const int& h = image.GetHeight();

		feature_map.reset(new Table<2,VecD>(h, w));
		for (int r = 0; r < h; r++) {
			const PixelRGB<byte>* row = image[r];
			for (int c = 0; c < w; c++) {
				VecD& ftr = (*feature_map)(r, c);
				ftr.Resize(3);
				if (r > 0 && r < h-1 && c > 0 && c < w-1) {
					int i = 0;
					ftr[i++] = imagehsv[r][c].h;
					ftr[i++] = imagehsv[r][c].s;
					ftr[i++] = imagehsv[r][c].v;
					/*ftr[i++] = imagehsv[r-1][c-1].v - ftr[1];
					ftr[i++] = imagehsv[r-1][c].v - ftr[1];
					ftr[i++] = imagehsv[r-1][c+1].v - ftr[1];
					ftr[i++] = imagehsv[r][c-1].v - ftr[1];
					ftr[i++] = imagehsv[r][c+1].v - ftr[1];
					ftr[i++] = imagehsv[r+1][c-1].v - ftr[1];
					ftr[i++] = imagehsv[r+1][c].v - ftr[1];
					ftr[i++] = imagehsv[r+1][c+1].v - ftr[1];*/
				} else {
					ftr.Fill(0);
				}

				features.push_back(ftr);
			}
		}
	}
Esempio n. 5
0
	void OutputGradientViz(const string& filename,
												 const ImageRGB<byte>& image) const {
		const int& w = image.GetWidth();
		const int& h = image.GetHeight();

		// Draw segment boundaries
		ImageRGB<byte> canvas;
		const MatI& segmap = segmentation;
		ImageCopy(image, canvas);
		for (int r = 0; r < h; r++) {
			for (int c = 0; c < w; c++) {
				if (distxform.dists[r][c] == 0) {
					canvas[r][c] = BrightColors::Get(segmap[r][c]);
				}
			}
		}

		// Draw segment orientation
		for (int i = 0; i < num_segments; i++) {
			if (seg_sizes[i] > 40) {
				const double norm = 10.0 / sqrt(seg_dx[i]*seg_dx[i] + seg_dy[i]*seg_dy[i]);
				Vector<2> a = makeVector(seg_x[i], seg_y[i]);
				Vector<2> b = makeVector(seg_x[i]+seg_dx[i]*norm, seg_y[i]+seg_dy[i]*norm);
				DrawSpot(canvas, BrightColors::Get(i), a, 1);
				DrawLineClipped(canvas, a, b, BrightColors::Get(i));
			}
		}
		WriteImage("out/segorients.png", canvas);
	}
Esempio n. 6
0
static std::pair<bool, String> save_png_gdiplus(const Path &filename, const ImageRGB &img)
{
	// gdi+ does not support URIs
	Path winname(filename);
	winname.ToWindows();
	const auto newsize = winname.Size() + 1;
	auto wcstring = std::vector<wchar_t>(newsize);
	auto convertedChars = size_t(0);
	mbstowcs_s(&convertedChars, wcstring.data(), newsize, winname.CStr(), _TRUNCATE);

	Gdiplus::Bitmap *outbm = new Gdiplus::Bitmap(INT(img.GetWidth()), INT(img.GetHeight()), PixelFormat24bppRGB);
	if (!outbm)
	{
		return std::make_pair(false, String(_("Cannot create bitmap")));
	}
	Gdiplus::BitmapData bitmapData;
	auto clip = Gdiplus::Rect(0, 0, outbm->GetWidth(), outbm->GetHeight());
	outbm->LockBits(&clip, Gdiplus::ImageLockModeWrite, PixelFormat24bppRGB, &bitmapData);
	auto *pixels = (uint8_t*)bitmapData.Scan0;
//#pragma omp parallel for
	FOREACHPIXEL(x, y, img)
	{
		size_t poffset = 3 * x + y * bitmapData.Stride;
		const auto &pix = img.At(x, y);
		pixels[poffset + 2] = pix.r;
		pixels[poffset + 1] = pix.g;
		pixels[poffset] = pix.b;
	}
Esempio n. 7
0
	void Compute(const ImageRGB<byte>& image, const ImageHSV<byte>& imagehsv) {
		const int& w = image.GetWidth();
		const int& h = image.GetHeight();
		label_map.Resize(h, w);

		// Compute pixel-wise features
		pixel_ftrs.Compute(image, imagehsv);

		// Run K-means to generate textons
		vector<VecD> points;
		const vector<VecD>& ftrs = pixel_ftrs.features;
		random_sample_n(ftrs.begin(), ftrs.end(), back_inserter(points), 5000);
		VecI labels(points.size());
		KMeans::Estimate(points, 20, textons, labels);

		// Label the pixels
		for (int r = 0; r < h; r++) {
			for (int c = 0; c < w; c++) {
				const VecD& ftr = (*pixel_ftrs.feature_map)(r, c);
				double mindist = INFINITY;
				for (int i = 0; i < textons.size(); i++) {
					const double dist = VectorSSD(textons[i], ftr);
					if (dist < mindist) {
						mindist = dist;
						label_map[r][c] = i;
					}
				}
			}
		}
	}
void YellowColorFilter::filterImage(ImageRGB & image) {
	// Image size;
	int width = image.width();
	int height = image.height();

	// For every pixel in the image
	for (int y = 0; y < height; y++) {
		for (int x = 0; x < width; x++) {
			// Get the RGB values
			Rgb<unsigned char &> pixelRGB = image.at(x, y);

			// To save the Hue, Saturation and Value
			float hue, saturation, value;

			// Convert RGB to HSV.
			RGB2HSV(pixelRGB.red, pixelRGB.green, pixelRGB.blue, hue, saturation, value);

			// If the color is yellow.
			if (hue >= 25 && hue <= 60 && saturation >= 0.60) {
				// If the color is within our yellow range, make the output pixel white.
				pixelRGB.red = 255;
				pixelRGB.green = 255;
				pixelRGB.blue = 255;
			}
			else {
				// Else make the pixel black.
				pixelRGB.red = 0;
				pixelRGB.green = 0;
				pixelRGB.blue = 0;
			}
		}
	}
}
Esempio n. 9
0
	// Invert alpha channel in an RGB image
	void InvertAlpha(ImageRGB<byte>& image) {
		for (int y = 0; y < image.GetHeight(); y++) {
			PixelRGB<byte>* row = image[y];
			for (int x = 0; x < image.GetWidth(); x++) {
				row[x].alpha = 255-row[x].alpha;
			}
		}
	}
Esempio n. 10
0
void FrameCapturer::rgb2bgr(ImageRGB& img) {
  ImageRGB::pixel_type pix,pix_end;

  for(pix=img.begin(),pix_end=img.end();
      pix!=pix_end;
      ++pix)
    rgb2bgr(*pix);
}
Esempio n. 11
0
	void Draw(ImageRGB<byte>& canvas, const PixelRGB<byte>& color) const {
		const int nx = canvas.GetWidth();
		const int ny = canvas.GetWidth();
		const float theta = theta;
		const float rho = rho;

		canvas.SetPenColour(color);
		canvas.DrawLine(start[0], start[1], end[0], end[1]);
	}
Esempio n. 12
0
	void Compute(const ImageRGB<byte>& image,
							 const ImageHSV<byte>& imagehsv) {
		const int kNumBins = 5;
		const int& w = image.GetWidth();
		const int& h = image.GetHeight();
		label_map.Resize(h, w);
		for (int r = 0; r < h; r++) {
			for (int c = 0; c < w; c++) {
				label_map[r][c] = static_cast<int>
					(imagehsv[r][c].h * kNumBins / 256);
			}
		}
	}
Esempio n. 13
0
void init()
{
	std::string infile("images//distance.bmp");
	ImageRGB rgb = Imread(infile);
	width = rgb.GetWidth();
	height = rgb.GetHeight();
	pixelData = GetGLPixelData(rgb);

	glClearColor(0.0, 0.0, 0.0, 0.0);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluOrtho2D(0.0, width, 0.0, height);
}
Esempio n. 14
0
	void Compute(const ImageRGB<byte>& imagergb,
							 const MatI& seg,
							 int num_segs) {
		const int& w = imagergb.GetWidth();
		const int& h = imagergb.GetHeight();
		segmentation = seg;
		num_segments = num_segs;
		
		// Compute gradients
		ImageCopy(imagergb, imagemono);
		gradients.Compute(imagemono);
		distxform.Compute(seg);

		// Compute average gradient in each segment
		mask.Resize(h, w);
		mask.Fill(0);
		seg_x.Resize(num_segments, 0.0);
		seg_y.Resize(num_segments, 0.0);
		seg_dx.Resize(num_segments, 0.0);
		seg_dy.Resize(num_segments, 0.0);
		seg_sizes.Resize(num_segments, 0);
		for (int r = 0; r < h; r++) {
			const int* segrow = seg[r];
			const PixelF* dxrow = gradients.diffx[r];
			const PixelF* dyrow = gradients.diffy[r];
			const int* distrow = distxform.dists[r];
			for (int c = 0; c < w; c++) {
				if (distrow[c] >= 2) {
					const int seg = segrow[c];
					seg_x[seg] += c;
					seg_y[seg] += r;
					seg_dx[seg] += dxrow[c].y;  // "y" just means the value of the pixel
					seg_dy[seg] += dyrow[c].y;
					seg_sizes[seg]++;
					mask[r][c] = 1;
				}
			}
		}

		// Compose features and normalize
		features.resize(num_segments);
		for (int i = 0; i < num_segments; i++) {
			if (seg_sizes[i] > 0) {
				seg_x[i] /= seg_sizes[i];
				seg_y[i] /= seg_sizes[i];
				seg_dx[i] /= seg_sizes[i];
				seg_dy[i] /= seg_sizes[i];
			}
			features[i] = MakeVector<2,float>(seg_dx[i], seg_dy[i]);
		}
	}
Esempio n. 15
0
	void WriteImage(const std::string& file, const ImageRGB<byte>& image) {
		rgba8c_view_t v = interleaved_view(image.GetWidth(),
																			 image.GetHeight(),
																			 (const rgba8_pixel_t*)image.GetImageBuffer(),
																			 image.GetWidth()*sizeof(PixelRGB<byte>));
		// Here we use a hack to work around the fact that GIL uses
		// 255=opaque but we use 0=opaque
		InvertAlpha(const_cast<ImageRGB<byte>&>(image));
		if (IsJpegFilename(file)) {
			CHECK(false) << "jpeg output not supported";
			//jpeg_write_view(file, v);
		} else {
			png_write_view(file, v);
		}
		InvertAlpha(const_cast<ImageRGB<byte>&>(image));
	}
Esempio n. 16
0
static std::pair<bool, String> save_png_gdkpixbuf(const Path &fname, const ImageRGB &img)
{
	GdkPixbuf *pb = gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8, 
			int(img.GetWidth()), int(img.GetHeight()));
	if (!pb)
	{
		return std::make_pair(false, String(_("Cannot create temporary buffer.")));
	}

	int w = gdk_pixbuf_get_width(pb);
	int h = gdk_pixbuf_get_height(pb);
	int rs = gdk_pixbuf_get_rowstride(pb);
	guchar *ppix = gdk_pixbuf_get_pixels(pb);
	for (int y = 0; y < h; y++)
		for (int x = 0; x < w; x++)
		{
			const auto px = img.At(x, y);
			int o2 = x + x + x + y * rs;
			ppix[o2] = px.r;
			ppix[o2 + 1] = px.g;
			ppix[o2 + 2] = px.b;
		}

	GError *err = NULL;
	gchar *utfname;
	gsize i;
	utfname = g_locale_to_utf8(fname.CStr(), -1, NULL, &i, NULL);
	gchar *filename;
	filename = g_filename_from_utf8(utfname, -1, NULL, &i, NULL);
	g_free(utfname);
	gchar *tinfo = g_locale_to_utf8("tEXt::Source", -1, NULL, &i, NULL);
	gchar *tinfo2 = g_locale_to_utf8("Saved by libcrn.", -1, NULL, &i, NULL);
	bool ok = gdk_pixbuf_save(pb, filename, "png", &err, tinfo, tinfo2, NULL); 
	g_free(filename);
	g_free(tinfo);
	g_free(tinfo2);
	g_object_unref(pb);
	String out(U"");
	if (!ok)
	{
		out = String(_("Cannot save file. ")) + err->message;
		g_error_free(err);
	}
	return std::make_pair(ok, out);
}
Esempio n. 17
0
	void GlutWindow::CaptureFrameBuffer(ImageRGB<byte>& out) const {
		CHECK(InGlutThread())
			<< "Frame buffer can only be captured inside the GLUT thread.";
		Flush();
		ResizeImage(out, size_);
		glReadPixels(0, 0, size_.x, size_.y,
								 GL_BGRA, GL_UNSIGNED_BYTE, out.GetImageBuffer());
		ResetAlpha(out);  // the GL convention for alpha is different to ours
		FlipVertical(out);  // the GL convention for top and bottom is different to ours
	}
ImageGray GrayscaleImage::convertToGrayscale(ImageRGB & image) {
	// Image size.
	int width = image.width();
	int height = image.height();

	// The destination image.
	ImageGray grayImage(width, height);

	// For every pixel in the image.
	for (int y = 0; y < height; y++) {
		for (int x = 0; x < width; x++) {
			// Get the pixel at position x,y.
			Rgb<unsigned char &> pixelRGB = image.at(x, y);
			unsigned char& pixelGray = grayImage.at(x, y);

			// Convert RGB to grayscale.
			pixelGray = pixelRGB.red * 0.114 + pixelRGB.green * 0.587 + pixelRGB.blue * 0.299;
		}
	}
	
	// Return the gray image.
	return grayImage;
}
Esempio n. 19
0
std::unique_ptr<ImageRGB> imageTransform::convert(const ImageRGB& oldImage) {
	std::unique_ptr<ImageRGB> returnImage = std::make_unique<ImageRGB>(460, 110);

	matrix m;

	float *inverse = m.getInverseMatrix(theMatrix);

	float a0 = inverse[0];
	float a1 = inverse[1];
	float a2 = inverse[2];
	float b0 = inverse[3];
	float b1 = inverse[4];
	float b2 = inverse[5];
	float c0 = inverse[6];
	float c1 = inverse[7];
	float c2 = inverse[8];

#define PT_IN_IMAGE(x,y) (x >= 0 && x < oldImage.width() && y >= 0 && y < oldImage.height())
	for (int h = 0; h < returnImage->height(); ++h) {
		for (int w = 0; w < returnImage->width(); ++w) {
			float x = (a0*w) + (a1*h) + a2;
			float y = (b0*w) + (b1*h) + b2;
			float w1 = (c0*w) + (c1*h) + c2;

			x /= w1;
			y /= w1;

			if (PT_IN_IMAGE((int)x, (int)y)){ // wh naar xy fix - lars
				float x0 = floor(x);
				float x1 = ceil(x);
				float y0 = floor(y);
				float y1 = ceil(y);
				float deltaX = (x - x0);
				float deltaY = (y - y0);

				float p = oldImage.at((int)x0 + .5, (int)y0 + .5).red + (oldImage.at((int)x1 + .5, (int)y0 + .5).red - oldImage.at((int)x0 + .5, (int)y0 + .5).red) * deltaX;
				float q = oldImage.at((int)x0 + .5, (int)y1 + .5).red + (oldImage.at((int)x1 + .5, (int)y1 + .5).red - oldImage.at((int)x0 + .5, (int)y1 + .5).red) * deltaX;
				returnImage->at(w, h).red = (int)(p + ((q - p)*deltaY));

				p = oldImage.at((int)x0 + .5, (int)y0 + .5).green + (oldImage.at((int)x1 + .5, (int)y0 + .5).green - oldImage.at((int)x0 + .5, (int)y0 + .5).green) * deltaX;
				q = oldImage.at((int)x0 + .5, (int)y1 + .5).green + (oldImage.at((int)x1 + .5, (int)y1 + .5).green - oldImage.at((int)x0 + .5, (int)y1 + .5).green) * deltaX;
				returnImage->at(w, h).green = (int)(p + ((q - p)*deltaY));

				p = oldImage.at((int)x0 + .5, (int)y0 + .5).blue + (oldImage.at((int)x1 + .5, (int)y0 + .5).blue - oldImage.at((int)x0 + .5, (int)y0 + .5).blue) * deltaX;
				q = oldImage.at((int)x0 + .5, (int)y1 + .5).blue + (oldImage.at((int)x1 + .5, (int)y1 + .5).blue - oldImage.at((int)x0 + .5, (int)y1 + .5).blue) * deltaX;
				returnImage->at(w, h).blue = (int)(p + ((q - p)*deltaY));

			}

		}
	}

	return returnImage;
}
Esempio n. 20
0
void MatlabArrayToImage(const mxArray* m, ImageRGB<byte>& image) {
	CHECK(mxIsDouble(m)) << "Only images of double type are supported at present";
	VecI dims = GetMatlabArrayDims(m);
	CHECK_EQ(dims.Size(), 3) << "MatlabArrayToImage expects a H x W x 3 array";
	CHECK_EQ(dims[2], 3) << "MatlabArrayToImage expects a H x W x 3 array";
	image.AllocImageData(dims[1], dims[0]);
	double* p = mxGetPr(m);
	for (int x = 0; x < dims[1]; x++)
		for (int y = 0; y < dims[0]; y++)
			image[y][x].r = *p++ * 255;  // pixels of type double are in [0,1] under matlab
	for (int x = 0; x < dims[1]; x++)
		for (int y = 0; y < dims[0]; y++)
			image[y][x].g = *p++ * 255;  // pixels of type double are in [0,1] under matlab
	for (int x = 0; x < dims[1]; x++)
		for (int y = 0; y < dims[0]; y++)
			image[y][x].b = *p++ * 255;  // pixels of type double are in [0,1] under matlab
	for (int x = 0; x < dims[1]; x++)
		for (int y = 0; y < dims[0]; y++)
			image[y][x].alpha = 0;
}
Esempio n. 21
0
bool CC(std::vector<CCStats> &ccstats, const ImageGray<BYTE> &imgbi, ImageRGB<BYTE> &imgFeedback)
{
    ImageGray<BYTE> img_copy(imgbi);
    std::vector<Pixel> firstPixels;
    double meansize = 0;
    for (int i = 0; i < imgbi.xsize(); i++) {
        for (int j = 0; j < imgbi.ysize(); j++) {
            std::vector<Pixel> ccC;
            CCStats stats;
            int npix = extract_cc_(Pixel(i, j), ccC, img_copy);
            if (npix > 180) {
                extract_CCStats(ccC, stats, imgbi);
                double compactness = 4*PI*stats.nPoints / (stats.perimeter*stats.perimeter);
                // !!compactness < 1.3 is not a good limit! I changed to 1.5 -Leman
                if (std::min(stats.radius1,
                             stats.radius2) > 8 && compactness < 1.5 && compactness > 0.7) {
                    ccstats.push_back(stats);
                    firstPixels.push_back(Pixel(i, j));
                    meansize += stats.nPoints;
                    // draw Feedback
                    for (int k = 0; k < ccC.size(); ++k) {
                        Pixel p = ccC[k];
                        // black means detected
                        imgFeedback.pixel_R(p.x, p.y) = 0;
                        imgFeedback.pixel_G(p.x, p.y) = 0;
                        imgFeedback.pixel_B(p.x, p.y) = 0;
                    }
                } else {
                    // draw Feedback
                    for (int k = 0; k < ccC.size(); ++k) {
                        Pixel p = ccC[k];
                        // red means it's not a circle
                        imgFeedback.pixel_R(p.x, p.y) = 150;
                        imgFeedback.pixel_G(p.x, p.y) = 0;
                        imgFeedback.pixel_B(p.x, p.y) = 0;
                    }
                }
            } else {
                // draw Feedback
                for (int k = 0; k < ccC.size(); ++k) {
                    Pixel p = ccC[k];
                    // green means it's too small
                    imgFeedback.pixel_R(p.x, p.y) = 0;
                    imgFeedback.pixel_G(p.x, p.y) = 150;
                    imgFeedback.pixel_B(p.x, p.y) = 0;
                }
            }
        }
        double percent = ((double)i / (double)imgbi.xsize())*100;
        if (!(i % (int)(0.2*imgbi.xsize()+1)))
            libMsg::cout<<(int)(percent+1)<<'%'<<libMsg::flush;
        else if (!(i % (int)(0.04*imgbi.xsize()+1)))
            libMsg::cout<<'.'<<libMsg::flush;
    }
    libMsg::cout<<libMsg::endl;

    if (ccstats.size() == 0) {
        libMsg::cout<<"Nothing interesting found in this image. Please check.";
        return false;
    }
    // retrieve min_size and max_size to build a size histogram
    int max_val = 0;
    int rad_thre = 7;
    for (int i = 0; i < ccstats.size(); i++) {
        if (ccstats[i].nPoints > max_val)
            max_val = ccstats[i].nPoints;
    }

    std::vector<int> hist(max_val);
    std::vector<std::stack<int> > hist_stack(max_val); // to keep indeces of all the circles for given size
    // run through all the sizes and build frequency histogram
    for (int i = 0; i < ccstats.size(); i++) {
        int val = ccstats[i].nPoints-1;
        hist[val]++;
        hist_stack[val].push(i);
    }

    meansize /= ccstats.size();
    int commonsize = meansize;
    libMsg::cout<<"Average area of region: "<<meansize<<" pixels"<<libMsg::endl;
    libMsg::cout<<"Max area of region: "<<max_val<<" pixels"<<libMsg::endl;
    libMsg::cout<<"Region found before filter: [ "<<ccstats.size()<<" ]"<<libMsg::endl;
    /*
     *  frequency
     *   ^
     *   |
     *   |
     *   |               |
     *   |               | |           larger than zerogap
     *   |               | |           so we ignore A and B
     *   |   <--->  | ||||| |   |    <--------------->
     *   |  A     | | ||||| ||  |   |                 B
     *   ----------------------------------------------------> size
     *   0               ^                                10000
     *                   |
     *              average size
     *   negative   <---- ---->  positive
     *   direction               direction
     */
    // collect the inliers in positive direction from commonsize idx

    int zerosgap = meansize/5;
    int count = 0;
    int flag = zerosgap;
    std::vector<int> inliers(ccstats.size());
    while (flag != 0 && commonsize+count < hist.size()) {
        int hist_idx = commonsize + count;
        int onesizecircles = hist[hist_idx];
        if (onesizecircles == 0) {
            flag--;
        } else {
            while (!hist_stack[hist_idx].empty()) {
                inliers[hist_stack[hist_idx].top()] = 1;
                // inliers.push(hist_stack[hist_idx].top());
                hist_stack[hist_idx].pop();
            }
            flag = zerosgap;
        }
        count++;
    }

    // collect the inliers in negative direction from commonsize idx
    count = -1;
    flag = zerosgap;
    while (flag != 0 && commonsize+count >= 0) {
        int hist_idx = commonsize + count;
        int onesizecircles = hist[hist_idx];
        if (onesizecircles == 0) {
            flag--;
        } else {
            while (!hist_stack[hist_idx].empty()) {
                inliers[hist_stack[hist_idx].top()] = 1;
                hist_stack[hist_idx].pop();
            }
            flag = zerosgap;
        }
        count--;
    }

    std::vector<CCStats> erasedCCStats;
    std::vector<int> outliersIdx;
    int idx = 0;
    while (idx < ccstats.size()) {
        if (inliers[idx] == 0) {
            erasedCCStats.push_back(ccstats[idx]);
            outliersIdx.push_back(idx);
            ccstats.erase(ccstats.begin() + idx);
            inliers.erase(inliers.begin() + idx);
        } else {
            idx++;
        }
    }
    libMsg::cout<<"Region found after filter: [ "<<ccstats.size()<<" ]"<<libMsg::endl;
    if (erasedCCStats.size() > 0) {
        libMsg::cout<<"Erased circles:"<<libMsg::endl;
        ImageGray<BYTE> img_copy2(imgbi);
        for (int i = 0; i < erasedCCStats.size(); ++i) {
            CCStats &stats = erasedCCStats[i];
            libMsg::cout<<"circle "<<i<<libMsg::endl;
            libMsg::cout<<"\tarea: "<<stats.nPoints<<libMsg::endl;
            libMsg::cout<<"\tcenter: "<<stats.centerX<<", "<<stats.centerY<<libMsg::endl;
            int index = outliersIdx[i];
            Pixel first = firstPixels[index];
            std::vector<Pixel> ccC;
            extract_cc_(first, ccC, img_copy2);
            for (int k = 0; k < ccC.size(); ++k) {
                Pixel p = ccC[k];
                // blue means filtered
                imgFeedback.pixel_R(p.x, p.y) = 0;
                imgFeedback.pixel_G(p.x, p.y) = 0;
                imgFeedback.pixel_B(p.x, p.y) = 150;
            }
        }
    }
    return true;
}
Esempio n. 22
0
	void saveImg(const ImageRGB & img, const std::string filename)
	{
		CImg<unsigned char> cimg(img.data(0, 0, Channel::Red), img.width(), img.height(), 1, 3);

		cimg.save(filename.c_str());
	}
Esempio n. 23
0
static std::pair<bool, String> save_png_libpng(const Path &filename, const ImageRGB &img)
{
	// libpng does not support URIs
	Path fname(filename);
	fname.ToLocal();

	std::unique_ptr<FILE, decltype(fclose_if_not_null)*> fp(fopen(fname.CStr(), "wb"), fclose_if_not_null);
	if (!fp)
	{
		return std::make_pair(false, String(_("Cannot create file ")) + U"<" + fname + U">");
	}

	/* Create png struct & info */
	png_structp png_ptr = png_create_write_struct (PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
	if (!png_ptr)
	{
		return std::make_pair(false, String(_("Cannot create the PNG structure.")));
	}
	png_infop info_ptr = png_create_info_struct(png_ptr);
	if (!info_ptr)
	{
		png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
		return std::make_pair(false, String(_("Cannot create the PNG info.")));
	}

	/* Set up the error handling */
	if (setjmp(png_jmpbuf(png_ptr)))
	{
		png_destroy_write_struct(&png_ptr, &info_ptr);
		return std::make_pair(false, String(_("Error while generating the PNG image.")));
	}

	/* setup libpng for using standard C fwrite() function with our FILE pointer */
	png_init_io(png_ptr, fp.get());

	/* Fill in the png_info structure */
	int width = int(img.GetWidth());
	int height = int(img.GetHeight());
	int bit_depth = 8;
	int color_type = PNG_COLOR_TYPE_RGB;
	int interlace_type = PNG_INTERLACE_NONE;
	int compression_type = PNG_COMPRESSION_TYPE_DEFAULT;
	int filter_method = PNG_FILTER_TYPE_DEFAULT;
	png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth, color_type, interlace_type, compression_type, filter_method);

	/* Using the low-level write interface */
	png_write_info(png_ptr, info_ptr);
	png_bytepp row_pointers;
	row_pointers = (png_bytep*)malloc(sizeof(png_byte*) * height);
	for (int i = 0; i < height ; ++i)
	{
#if (PNG_LIBPNG_VER > 10300)
		row_pointers[i] = (png_bytep)calloc(1, png_get_rowbytes(png_ptr, info_ptr));
#else
		row_pointers[i] = (png_bytep)calloc(1, info_ptr->rowbytes);
#endif
	}

	/* Conversion */
#if (PNG_LIBPNG_VER > 10300)
	int channels = png_get_channels(png_ptr, info_ptr);
#else
	int channels = info_ptr->channels;
#endif
	for (int y = 0; y < height; y++)
		for (int x = 0; x < width; x++)
		{
			const auto px = img.At(x, y);
			row_pointers[y][x * channels] = px.r;
			row_pointers[y][x * channels + 1] = px.g;
			row_pointers[y][x * channels + 2] = px.b;
		}

	png_write_image(png_ptr, row_pointers);

	// TODO more options
	png_text txt[1];
	txt[0].compression = PNG_TEXT_COMPRESSION_NONE;
	txt[0].key = (char*)"creator";
	txt[0].text = (char*)"libcrn";
	txt[0].text_length = strlen(txt[0].text);
	png_set_text(png_ptr, info_ptr, txt, 1);

	png_write_end(png_ptr, info_ptr);
	png_destroy_write_struct(&png_ptr, &info_ptr);

	// free
	for (int i = 0; i < height ; ++i)
	{
		free(row_pointers[i]);
	}
	free(row_pointers);
	return std::make_pair(true, String(""));

}
std::unique_ptr<ImageGray> thresholdDetermination::convert(const ImageRGB& img){
	std::unique_ptr<ImageGray> returnImage = std::make_unique<ImageGray>(img.width(), img.height());
	meanCorners = (getIntensity(convertToHex(img.at(0, 0).red, img.at(0, 0).green, img.at(0, 0).blue)) + getIntensity(convertToHex(img.at(img.width() - 1, 0).red, img.at(img.width() - 1, 0).green, img.at(img.width() - 1, 0).blue)) + getIntensity(convertToHex(img.at(0, img.height() - 1).red, img.at(0, img.height() - 1).green, img.at(0, img.height() - 1).blue))) + getIntensity(convertToHex(img.at(img.width() - 1, img.height() - 1).red, img.at(img.width() - 1, img.height() - 1).green, img.at(img.width() - 1, img.height() - 1).blue)) / 4;
	meanAllOthers = 0;

	for (int h = 0; h < img.height(); ++h) {
		for (int w = 0; w < img.width(); ++w) {

			if (!((w == 0 && h == 0) || (w == img.width() - 1 && h == 0) || (w == 0 && h == img.height() - 1) || (w == img.width() - 1 && h == img.height() - 1))) {
				meanAllOthers += getIntensity(convertToHex(img.at(w, h).red, img.at(w, h).green, img.at(w, h).blue));
			}

		}
	}

	meanAllOthers /= ((img.width()*img.height()) - 4);

	tOld = 0;
	tNew = (meanCorners + meanAllOthers) / 2;


	unsigned int u1count = 0, u2count = 0;

	while (tNew != tOld) {

		meanAllOthers = 0;
		meanCorners = 0;
		for (int h = 0; h < img.height(); ++h) {
			for (int w = 0; w < img.width(); ++w) {


				if (getIntensity(convertToHex(img.at(w, h).red, img.at(w, h).green, img.at(w, h).blue)) < tNew){
					meanCorners += getIntensity(convertToHex(img.at(w, h).red, img.at(w, h).green, img.at(w, h).blue));
					u1count++;
				}
				else if (getIntensity(convertToHex(img.at(w, h).red, img.at(w, h).green, img.at(w, h).blue)) >= tNew){
					meanAllOthers += getIntensity(convertToHex(img.at(w, h).red, img.at(w, h).green, img.at(w, h).blue));
					u2count++;
				}

			}
		}
		if (u1count != 0){ 
			meanCorners /= u1count;		// HOTFIX - lars u1count kan nul zijn....
		}
		if (u2count != 0){
			meanAllOthers /= u2count;	// HOTFIX - lars u2count kan nul zijn....
		}
		
		u1count = 0;
		u2count = 0;
		tOld = tNew;
		tNew = (meanCorners + meanAllOthers) / 2;

	}

	for (int h = 0; h < returnImage->height(); ++h) {
		for (int w = 0; w < returnImage->width(); ++w) {

			if (getIntensity(convertToHex(img.at(w, h).red, img.at(w, h).green, img.at(w, h).blue)) < tNew){
				returnImage->at(w, h) = 0;
			}
			else if (getIntensity(convertToHex(img.at(w, h).red, img.at(w, h).green, img.at(w, h).blue)) >= tNew){
				returnImage->at(w, h) = 255;
			}

		}
	}

	return returnImage;

}
Esempio n. 25
0
int main(int argc, char* argv[]) {
    std::string hostname,user,password;
    int port;
    double pan,tilt,zoom;

    if(argc!=10) {
        std::cout << "Usage :" << std::endl
                  << "  " << argv[0]
                  << " <hostname> <port:80> <username> <password> <pan> <tilt> <zoom> <x> <y>"
                  << std::endl;
        return 0;
    }

    hostname = argv[1];
    port     = atoi(argv[2]);
    user     = argv[3];
    password = argv[4];

    axis::PTZ axis(hostname,port);
    if(!axis.connect(user,password)) {
        std::cout << "Connot connect " << user
                  << " (" << password << ") on "
                  << hostname << ':' << port << ". Aborting."
                  << std::endl;
        return 1;
    }

    axis.setAutoiris("off");
    axis.setIris(1000);

    axis.getPosition(pan,tilt,zoom);
    std::cout << "Current position is " << std::endl
              << "  pan  = " << pan << std::endl
              << "  tilt = " << tilt << std::endl
              << "  zoom = " << zoom << std::endl;

    pan  = atof(argv[5]);;
    tilt = atof(argv[6]);
    zoom = atof(argv[7]);

    std::cout << "Reaching now... " << std::endl
              << "  pan  = " << pan << std::endl
              << "  tilt = " << tilt << std::endl
              << "  zoom = " << zoom << std::endl;
    axis.setPanTilt(pan,tilt);
    axis.setZoom(zoom);
    axis.wait();

    std::cout << "... reached." << std::endl;
    axis.getPosition(pan,tilt,zoom);
    std::cout << "  pan  = " << pan << std::endl
              << "  tilt = " << tilt << std::endl
              << "  zoom = " << zoom << std::endl;

    // Let us now grab an image.
    // We wait 2 seconds for autofocus to stabilize, since we mah have zoomed.
    ost::Thread::sleep(2000);
    axis.getDefaultBMPImage();

    // Let us now handle the image with mirage
    ImageRGB img;
    int dummy;
    mirage::img::Coordinate img_size(axis.getWidth(),axis.getHeight());
    img.resize(img_size,
               (ImageRGB::value_type*)axis.getImageBytes(dummy,dummy,dummy));

    // Let is save the mirage image in a file.
    std::ostringstream outputnamestream;
    outputnamestream << "X_" << argv[8] << "Y_" << argv[9] << "pan_" << pan << "tilt_" << tilt << "zoom_" << zoom << ".jpg";
    std::string outputname = outputnamestream.str();
    rgb2bgr(img);
    mirage::img::JPEG::write(img,outputname,80);
    std::cout << "Image has been captured in ptz.jpg file." << std::endl;

    return 0;
}
void Application::getScreenShot(ImageRGB& img) {
    int w = 0, h = 0;
    glfwGetFramebufferSize(context->window, &w, &h);
    img.resize(w, h);
    glReadPixels(0, 0, w, h, GL_RGB, GL_UNSIGNED_BYTE, img.ptr());
}