std::unique_ptr<Image> fitImageTo(const std::unique_ptr<Image>& image, int w, int h)
    {
        int tw = image->getWidth();
        int th = image->getHeight();
        int pw = (w * image->getHeight()) / h;
        int ph = (h * image->getWidth()) / w;

        if (ph <= th)
        {
            auto middle_img = cropImage(image, 0, th/2 - ph/2, tw, ph);
            return shrinkImage(middle_img, w);
        }
        auto middle_img = cropImage(image, tw/2 - pw/2, 0, pw, th);
        return shrinkImage(middle_img, w);
    }
int
main (int argc, char **argv)
{

  VERBOSE = 1;

  struct params p;
  processArgsAnalyze (argc, argv, p);
  gsl_matrix *atomsNonCrop = ReadFitsImg_gsl_matrix (p.atomsfile);
  //gsl_matrix *noatoms = ReadFitsImg_gsl_matrix (p.noatomsfile);


  gsl_matrix *atoms = cropImage (p.reportfile, atomsNonCrop);
  //gsl_matrix *cnoatoms = cropImage (p.reportfile, noatoms);

  double com[2];
  COM (atoms, com);

  cout << "COM_X = " << com[0] << endl;
  cout << "COM_Y = " << com[1] << endl;

  setINI_num (p.reportfile, "CPP", "COM_X", com[0]);
  setINI_num (p.reportfile, "CPP", "COM_Y", com[1]);

  gsl_matrix_free (atomsNonCrop);
  gsl_matrix_free (atoms);

}
Beispiel #3
0
IplImage* cropImage(const IplImage *src, const CvRect region, IplImage** pdst)
{
	if (*pdst != NULL)
		cvReleaseImage(pdst);
	*pdst = cropImage(src, region);
	return *pdst;
}
Beispiel #4
0
ImageBitmap::ImageBitmap(Image* image, const IntRect& cropRect)
    : m_imageElement(nullptr)
    , m_cropRect(cropRect)
{
    IntRect srcRect = intersection(cropRect, IntRect(IntPoint(), image->size()));
    m_bitmap = cropImage(image, cropRect);
    m_bitmapRect = IntRect(IntPoint(std::max(0, -cropRect.x()), std::max(0, -cropRect.y())),  srcRect.size());
}
Beispiel #5
0
cv::Mat stichImages (cv::Mat imgInput1, std::vector<cv::Point2f> &inlierPoints1, cv::Mat imgInput2, std::vector<cv::Point2f> &inlierPoints2)
{
    cv::Mat H = cv::findHomography(cv::Mat(inlierPoints2),
                                   cv::Mat(inlierPoints1),
                                   cv::FM_RANSAC,
                                   1.0);
    // Use the Homography Matrix to warp the images
    // std::cout << "H**o: " << H << std::endl;
    cv::Mat warpImage;
    cv::warpPerspective(imgInput2, warpImage, H, cv::Size(imgInput2.cols, imgInput2.rows), cv::INTER_CUBIC);

    // cv::imwrite("warp.jpg", warpImage2);
    // cv::Mat finalHomo(cv::Size(imgInput2.cols * 2 + imgInput1.cols, imgInput2.rows * 2), imgInput2.type());
    // cv::imwrite("finalHomo.jpg", finalHomo);
    // cv::Mat roi1(finalHomo, cv::Rect(0, 0,  imgInput1.cols, imgInput1.rows));
    // cv::Mat roi2(finalHomo, cv::Rect(0, 0, warpImage2.cols, warpImage2.rows));
    // cv::imwrite("roi1.jpg", roi1);
    // cv::imwrite("roi2.jpg", roi2);
    // warpImage2.copyTo(roi2);
    // cv::imwrite("roi2.jpg", roi2);
    // imgInput1.copyTo(roi1);
    // cv::imwrite("roi1.jpg", roi1);
    // cv::imwrite("finalHomo.jpg", finalHomo);

    cv::Mat cropImage(warpImage, cv::Rect(0 , 0, imgInput1.cols, imgInput1.rows));
    return cropImage;

    /// crop over the finalHomo
    // int colInx = 0;
    // for (size_t i(0); i < finalHomo.cols; i++)
    // {

    //     cv::Scalar res = cv::sum(finalHomo.col(i));
    //     if (res[0] == 0)
    //     {
    //         colInx = i;
    //         break;
    //     }
    // }
    // std::cout << "Col Inx: " << colInx << std::endl;

    // int rowInx = 0;
    // for (size_t i(0); i < finalHomo.rows; i++)
    // {

    //     cv::Scalar res = cv::sum(finalHomo.row(i));
    //     if (res[0] == 0)
    //     {
    //         rowInx = i;
    //         break;
    //     }
    // }
    // std::cout << "Row Inx: " << rowInx << std::endl;

    // cv::Mat cropImage(finalHomo, cv::Rect(0 , 0, colInx, rowInx));
    // return cropImage;
}
Beispiel #6
0
ImageBitmap::ImageBitmap(HTMLCanvasElement* canvas, const IntRect& cropRect)
    : m_imageElement(nullptr)
    , m_cropRect(cropRect)
    , m_bitmapOffset(IntPoint())
{
    IntRect srcRect = intersection(cropRect, IntRect(IntPoint(), canvas->size()));
    m_bitmapRect = IntRect(IntPoint(std::max(0, -cropRect.x()), std::max(0, -cropRect.y())), srcRect.size());
    ASSERT(canvas->isPaintable());
    m_bitmap = cropImage(canvas->copiedImage(BackBuffer).get(), cropRect);
}
Beispiel #7
0
ImageBitmap::ImageBitmap(Image* image, const IntRect& cropRect)
    : m_cropRect(cropRect)
    , m_imageElement(0)
{
    IntRect srcRect = intersection(cropRect, IntRect(IntPoint(), image->size()));
    m_bitmap = cropImage(image, cropRect);
    m_bitmapRect = IntRect(IntPoint(max(0, -cropRect.x()), max(0, -cropRect.y())),  srcRect.size());

    ScriptWrappable::init(this);
}
void Main::mainLoop(){
    
    frame = cvQueryFrame( capture );
    cvResize(frame, resized);
    
	while(detector.detectFace(resized,&box)==0)
	{
		frame = cvQueryFrame( capture );
		cvResize(frame, resized);
	}
    
    while(1){
        frame = cvQueryFrame( capture );
        cvResize(frame, resized);
        
        if(!initialized){
            detector.detectFace(resized,&box);
            cropImage(resized, &imgTemplate, box);
            tempMatcher.Initializer(resized,&imgTemplate);
            initialized = true;
        }
        //printf("main loop\n");
        if(initialized){
            prob = tempMatcher.matchTemplate(resized, &center);
			for(int i=0;i<4;i++)
			{
				averageProb[i]=averageProb[i+1];
			}
			averageProb[4]=prob;
			prob=0;
			for(int i=0;i<5;i++)
			{
				prob+=averageProb[i];
			}
			prob/=5;
            count++;
            if(prob<minprob ||(prob>maxprob && count > 5) || count > 1000){
				printf("Point %lf\n =",prob);
                initialized = false;
				count=0;
            }
            
			cvRectangle(resized, cvPoint(center.x, center.y), cvPoint(center.x+box.width, center.y+box.height), cvScalar(100));
            sprintf(text, "X = %d  Y = %d ", center.x,center.y);
            textWriter.printText(resized,text, cvPoint(center.x,center.y));
            sprintf(text, "Prob = %lf", prob);
            textWriter.printText(resized,text, cvPoint(100,100));
            cvShowImage(name, resized);
        }
        
        if( cvWaitKey( 15 )==27 ) 
            break;
    }
        
}
Beispiel #9
0
gui::gui(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::gui)
{
    ui->setupUi(this);
    m_hiddenMonitor = new QTimer(this);
    m_hiddenMonitor->setInterval(50);

    QObject::connect(m_hiddenMonitor, SIGNAL(timeout()), this, SLOT(OnHiddenMonitorTimeout()));
    QObject::connect(ui->cropImageButton, SIGNAL(clicked()), this, SLOT(cropImage()));
    QObject::connect(ui->processButton, SIGNAL(clicked()), this, SLOT(process()));
}
Beispiel #10
0
ImageBitmap::ImageBitmap(HTMLCanvasElement* canvas, const IntRect& cropRect)
    : m_imageElement(nullptr)
    , m_cropRect(cropRect)
    , m_bitmapOffset(IntPoint())
{
    CanvasRenderingContext* sourceContext = canvas->renderingContext();
    if (sourceContext && sourceContext->is3d())
        sourceContext->paintRenderingResultsToCanvas();

    IntRect srcRect = intersection(cropRect, IntRect(IntPoint(), canvas->size()));
    m_bitmapRect = IntRect(IntPoint(std::max(0, -cropRect.x()), std::max(0, -cropRect.y())), srcRect.size());
    m_bitmap = cropImage(canvas->buffer()->copyImage(CopyBackingStore).get(), cropRect);
}
Beispiel #11
0
ImageBitmap::ImageBitmap(ImageBitmap* bitmap, const IntRect& cropRect)
    : m_imageElement(bitmap->imageElement())
    , m_bitmap(nullptr)
    , m_cropRect(cropRect)
    , m_bitmapOffset(IntPoint())
{
    IntRect oldBitmapRect = bitmap->bitmapRect();
    IntRect srcRect = intersection(cropRect, oldBitmapRect);
    m_bitmapRect = IntRect(IntPoint(std::max(0, oldBitmapRect.x() - cropRect.x()), std::max(0, oldBitmapRect.y() - cropRect.y())), srcRect.size());

    if (m_imageElement) {
        m_imageElement->addClient(this);
        m_bitmapOffset = srcRect.location();
    } else if (bitmap->bitmapImage()) {
        IntRect adjustedCropRect(IntPoint(cropRect.x() -oldBitmapRect.x(), cropRect.y() - oldBitmapRect.y()), cropRect.size());
        m_bitmap = cropImage(bitmap->bitmapImage().get(), adjustedCropRect);
    }
}
Beispiel #12
0
MainUI::MainUI() : QMainWindow(), ui(new Ui::MainUI){
  ui->setupUi(this); //load the designer file
  mousegrabbed = false;
  XCB = new LXCB();
  IMG = new ImageEditor(this);
  ui->scrollArea->setWidget(IMG);
  ui->tabWidget->setCurrentWidget(ui->tab_view);
  ppath = QDir::homePath();

  setupIcons();
  ui->spin_monitor->setMaximum(QApplication::desktop()->screenCount());
  if(ui->spin_monitor->maximum()<2){
    ui->spin_monitor->setEnabled(false);
    ui->radio_monitor->setEnabled(false);
  }	  

  //Setup the connections
  connect(ui->tool_save, SIGNAL(clicked()), this, SLOT(saveScreenshot()) );
  connect(ui->actionSave_As, SIGNAL(triggered()), this, SLOT(saveScreenshot()) );
  connect(ui->tool_quicksave, SIGNAL(clicked()), this, SLOT(quicksave()) );
  connect(ui->actionQuick_Save, SIGNAL(triggered()), this, SLOT(quicksave()) );
  connect(ui->actionClose, SIGNAL(triggered()), this, SLOT(closeApplication()) );
  connect(ui->push_snap, SIGNAL(clicked()), this, SLOT(startScreenshot()) );
  connect(ui->actionTake_Screenshot, SIGNAL(triggered()), this, SLOT(startScreenshot()) );
  connect(ui->tool_crop, SIGNAL(clicked()), IMG, SLOT(cropImage()) );
  connect(IMG, SIGNAL(selectionChanged(bool)), this, SLOT(imgselchanged(bool)) );

  settings = new QSettings("lumina-desktop", "lumina-screenshot",this);
  if(settings->value("screenshot-target", "window").toString() == "window") {
	ui->radio_window->setChecked(true);
  }else{
	ui->radio_all->setChecked(true);
  }
  ui->spin_delay->setValue(settings->value("screenshot-delay", 0).toInt());

  ui->tool_resize->setVisible(false); //not implemented yet
  this->show();
  IMG->setDefaultSize(ui->scrollArea->maximumViewportSize());
  IMG->LoadImage( QApplication::screens().at(0)->grabWindow(QApplication::desktop()->winId()).toImage() ); //initial screenshot
  //ui->label_screenshot->setPixmap( cpic.scaled(ui->label_screenshot->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation) );
}
QPixmap GraphicsZone::loadPixmap(Pokemon::uniqueId num, bool shiny, bool back, quint8 gender, bool sub)
{
    quint64 key = this->key(num, shiny, back, gender, sub);

    if (!graphics.contains(key)) {
        QPixmap p;
        if (sub) {
            p = PokemonInfo::Sub(info()->gen(), back);
        } else {
            p = PokemonInfo::Picture(num, info()->gen(), gender, shiny, back);
        }

        QImage img = p.toImage();
        cropImage(img);
        p = QPixmap::fromImage(img);

        graphics.insert(key, p);
    }

    return graphics[key];
}
Beispiel #14
0
void initInputImage(const cv::Mat &img, DTYPE *mean, aocl_utils::scoped_aligned_ptr<DTYPE> &h_input_img) {
	// Resize image to be 256x256
	cv::Mat res_img;
	cv::Size size(256, 256);
	cv::resize(img, res_img, size);
	// mean normalization
	cv::Mat mean_norm = cv::Mat::zeros(size, CV_32FC3);
	DTYPE rm, gm, bm;
	cv::Vec3b pixel_u8;
	cv::Vec3f pixel_f;
	for(int r = 0; r < res_img.rows; r++) {
		for(int c = 0; c < res_img.cols; c++) {
			pixel_u8 = res_img.at<cv::Vec3b>(r,c);
			rm = mean[0*256*256+r*256+c];
			gm = mean[1*256*256+r*256+c];
			bm = mean[2*256*256+r*256+c];
			pixel_f.val[0] = pixel_u8.val[0] - bm;
			pixel_f.val[1] = pixel_u8.val[1] - gm;
			pixel_f.val[2] = pixel_u8.val[2] - rm;
			mean_norm.at<cv::Vec3f>(r,c) = pixel_f;
		}
	}	
	cv::Mat crop_img;

	cropImage(mean_norm, crop_img, 227, 227, CENTER);
    unsigned int C = crop_img.channels();
	unsigned int W = crop_img.cols;
	unsigned int H = crop_img.rows;
    for(int row = 0; row < H; row++) {
        for(int col = 0; col < W; col++) {
			pixel_f = crop_img.at<cv::Vec3f>(row,col);
			// BGR to RGB conversion will happen here by properly storing pixels in that manner.
			h_input_img[0*H*W + row*W + col] = pixel_f[2];
			h_input_img[1*H*W + row*W + col] = pixel_f[1];
			h_input_img[2*H*W + row*W + col] = pixel_f[0];
        }
    }
}
cv::Mat removeNoise(cv::Mat image){
	//scale image so we are always working with the same size
	//calculate the scale when it is scaled down to 128 pixels in height

	double scale = 128.0 / double(image.cols);

	cv::Mat imgResize = cv::Mat::zeros(image.rows * scale, image.cols * scale, image.type());
	for (int outY = 0; outY < imgResize.rows; outY++){
		for (int outX = 0; outX < imgResize.cols; outX++){
			imgResize.at<uchar>(outY, outX) = image.at<uchar>((1 / scale) * outY, (1 / scale) * outX);
		}
	}
	image = imgResize.clone();
	//Threshold after resize
	for (int y = 0; y < image.rows; y++){
		for (int x = 0; x < image.cols; x++){
			if (image.at<unsigned char>(y, x) >= 170){
				image.at<unsigned char>(y, x) = 0;
			}
			else{
				image.at<unsigned char>(y, x) = 255;
			}
		}
	}
	cv::Mat element = getStructuringElement(cv::MORPH_RECT,
		cv::Size(9, 9),
		cv::Point(4, 4));
	erode(image, image, element);
	dilate(image, image, element);
	imshow("after closing", image);

	image = cropImage(image);
	imshow("after crop", image);

	return image;
}
/*
*Contains algorithm to pixelate and image with given params
*Parameters:
*pixAmount: the amount to pixelate our image by
*img: a pointer to our image in memory.
*
*return 0 if no errors were encountered, 1 otherwise.
*/
int pixelate(Image* img, int pixAmount) {
	//if we don't have a file in memory, complain.
	if(img->data == NULL) {
	fprintf(stderr, "Error, no file currently in memory\n");
		return 1;
	}
	//ints that we can change without messing with our image
	int numCols = img->colNum;
	int numRows = img->rowNum;
	//this sets the variables above to ones evenly divisible by pixAmount
	while( ((numCols % pixAmount) != 0) || ((numRows % pixAmount) != 0)) {
		if((numCols % pixAmount) != 0) {
			numCols--;
		}
		if((numRows % pixAmount) != 0) {
			numRows--;
		}
	}
	//we crop our image, and lose the part that we can't easily pixelate. 
	cropImage(0,  numCols, 0, numRows, img);
	//set our number of pixels in our pixelated image
	numCols = numCols/pixAmount;
	numRows = numRows/pixAmount;
	//variables to compute what each pixel should be
	int pixSumR = 0;
	int pixSumG = 0;
	int pixSumB = 0;
	// the number of pixels in one "square" of our image
	int numPix = (int)sq(pixAmount);
	//for loop that loops through all the rows & cols of our pix'd image
	for(int j=0; j<numRows; j++) {
		for(int i=0; i<numCols; i++) {
			//these loops loop through each pixel of our image in memory, and change the pixSums as needed.
			for(int y=0; y<pixAmount; y++) {
				for(int x=0; x<pixAmount; x++) {
					pixSumR+=img->data[(j*pixAmount+y)*(img->colNum)+(i*pixAmount+x)].r;
					pixSumG+=img->data[(j*pixAmount+y)*(img->colNum)+(i*pixAmount+x)].g;
					pixSumB+=img->data[(j*pixAmount+y)*(img->colNum)+(i*pixAmount+x)].b;
				}
			}
		//averages it for each color
		pixSumR = (pixSumR/numPix);
		pixSumG = (pixSumG/numPix);
		pixSumB = (pixSumB/numPix);	
		//turns our image into a pixelated one with the (almost) same resolution as the original.
		for(int y=0; y<pixAmount; y++) {
				for(int x=0; x<pixAmount; x++) {
					img->data[(j*pixAmount+y)*(img->colNum)+(i*pixAmount+x)].r =pixSumR;
					img->data[(j*pixAmount+y)*(img->colNum)+(i*pixAmount+x)].g =pixSumG;
					img->data[(j*pixAmount+y)*(img->colNum)+(i*pixAmount+x)].b =pixSumB;
				}
			}
		//reset the sums
		pixSumR = 0;
		pixSumG = 0;
		pixSumB = 0;
		}
	}
	
	return 0; 
}
    void ContactAvatarWidget::cropAvatar()
    {
        QWidget *hostWidget = nullptr;
        QLayout *hostLayout = nullptr;

        QWidget *mainWidget = nullptr;
        QLayout *mainLayout = nullptr;

        if (imageCropHolder_)
        {
            hostWidget = new QWidget(this);
            hostLayout = new QHBoxLayout(hostWidget);
            hostWidget->setSizePolicy(QSizePolicy::Policy::Preferred, QSizePolicy::Policy::Fixed);
            hostWidget->setFixedHeight(imageCropSize_.height());
            hostLayout->setContentsMargins(Utils::scale_value(16), Utils::scale_value(12), Utils::scale_value(16), 0);

            mainWidget = new QWidget(hostWidget);
            mainLayout = Utils::emptyHLayout(mainWidget);
            mainWidget->setSizePolicy(QSizePolicy::Policy::Preferred, QSizePolicy::Policy::Preferred);
            hostLayout->addWidget(mainWidget);
        }
        else
        {
            mainWidget = new QWidget(this);
            mainLayout = new QHBoxLayout(mainWidget);
            mainLayout->setContentsMargins(Utils::scale_value(16), Utils::scale_value(12), Utils::scale_value(16), 0);
        }

        auto avatarCropper = new Ui::ImageCropper(mainWidget, imageCropSize_);
        avatarCropper->setProportion(QSizeF(1.0, 1.0));
        avatarCropper->setProportionFixed(true);
        avatarCropper->setBackgroundColor(CommonStyle::getFrameColor());
        if (!infoForSetAvatar_.croppingRect.isNull())
        {
            avatarCropper->setCroppingRect(infoForSetAvatar_.croppingRect);
        }
        avatarCropper->setImage(QPixmap::fromImage(infoForSetAvatar_.image));
        mainLayout->addWidget(avatarCropper);

        if (!imageCropHolder_)
        {
            hostWidget = mainWidget;
        }

        GeneralDialog imageCropDialog(hostWidget, imageCropHolder_ ? imageCropHolder_ : Utils::InterConnector::instance().getMainWindow());
        imageCropDialog.setObjectName(qsl("image.cropper"));
        if (imageCropHolder_)
        {
            imageCropDialog.setShadow(false);
            imageCropDialog.connect(&imageCropDialog, &GeneralDialog::moved, this, [=](QWidget *dlg)
            {
                emit Utils::InterConnector::instance().imageCropDialogMoved(dlg);
            });
            imageCropDialog.connect(&imageCropDialog, &GeneralDialog::resized, this, [=](QWidget *dlg)
            {
                emit Utils::InterConnector::instance().imageCropDialogResized(dlg);
            });
            imageCropDialog.connect(&imageCropDialog, &GeneralDialog::shown, this, [=](QWidget *dlg)
            {
                emit Utils::InterConnector::instance().imageCropDialogIsShown(dlg);
            });
            imageCropDialog.connect(&imageCropDialog, &GeneralDialog::hidden, this, [=](QWidget *dlg)
            {
                emit Utils::InterConnector::instance().imageCropDialogIsHidden(dlg);
            });
        }
        imageCropDialog.addHead();
        imageCropDialog.addLabel(mode_ == Mode::CreateChat ? QT_TRANSLATE_NOOP("avatar_upload", "Edit photo") : QT_TRANSLATE_NOOP("avatar_upload", "Upload photo"));
        imageCropDialog.addButtonsPair(QT_TRANSLATE_NOOP("popup_window", "BACK"), QT_TRANSLATE_NOOP("popup_window", "CONTINUE"), true, false, false);
        imageCropDialog.setRightButtonDisableOnClicked(true);

        QObject::connect(&imageCropDialog, &GeneralDialog::leftButtonClicked, this, [=, &imageCropDialog]()
        {
            imageCropDialog.reject();
            QTimer::singleShot(500, this, [=](){ emit summonSelectFileForAvatar(); });
        },
        Qt::QueuedConnection);
        QObject::connect(&imageCropDialog, &GeneralDialog::rightButtonClicked, this, [=, &imageCropDialog]()
        {
            auto croppedImage = avatarCropper->cropImage();
            auto croppingRect = avatarCropper->getCroppingRect();

            infoForSetAvatar_.croppedImage = croppedImage;
            infoForSetAvatar_.croppingRect = croppingRect;
            imageCropDialog.accept();

            if (auto p = imageCropDialog.takeAcceptButton())
                p->setEnabled(true);
        },
        Qt::QueuedConnection);
        QObject::connect(&imageCropDialog, &GeneralDialog::shown, this, [=](QWidget *dlg)
        {
            //
        },
        Qt::QueuedConnection);

        if (!imageCropDialog.showInPosition(-1, -1))
        {
            return;
        }

        if (mode_ == Mode::CreateChat)
        {
            infoForSetAvatar_.roundedCroppedImage = QPixmap();
            emit avatarDidEdit();
        }
        else
        {
            openAvatarPreview();
        }
    }
Beispiel #18
0
int main(int argc, char* argv[]){
	
	FILE* parameters;
	
	/* parameters of the gaussian */
	int width;
	int length;
	double amplitude;
	double x_0;
	double y_0;
	double sigma_x0;
	double sigma_y0;
	double a_0;
	double b_0;
	double c_0;
	int max,min;
	
	/* parameters for the cookie cutter */
	double x0,y0;
	double FWHM_x,FWHM_y;
	int span_x,span_y;
	int dimx,dimy;
	int x,y;
	
	/* gaussian struct */
	fit_t results,test_g;
	
	/* indexes */
	int i,j;
	int temp;
	
	if(argc != 2){
		printf("NUMERO PARAMETRI INVALIDO\n");
		exit(EXIT_FAILURE);
	}
	
	parameters = fopen(argv[1],"r");
	
	/* LETTURA DEI PARAMETRI */
	fscanf(parameters,"%d\t%d\t",&width,&length);
	fscanf(parameters,"%lf\t%lf\t%lf\t",&amplitude,&x_0,&y_0);
	fscanf(parameters,"%lf\t%lf\t",&sigma_x0,&sigma_y0);
	fscanf(parameters,"%lf\t%lf\t%lf",&a_0,&b_0,&c_0);
	
	/* GAUSSIAN_MATRIX */
	unsigned char matrix[length][width];
	
#if DEBUG
	/* STAMPA DI DEBUG DEI PARAMETRI DELLA GAUSSIANA DA INTERPOLARE */
	printf("Dimensioni della matrice: %d %d\n",width,length);
	printf("Ampiezza: %f\nPosizione asse X: %f\nPosizione asse Y: %f\n",amplitude,x_0,y_0);
	printf("Varianza asse X: %f\nVarianza asse Y: %f\n",sigma_x0,sigma_y0);
	printf("A(x): %f\nB(y): %f\nC: %f\n",a_0,b_0,c_0);
#endif	
	
	/* ASSEGNAZIONE ALLA STRUCT */
	results.A = amplitude;
	results.x_0 = x_0;
	results.y_0 = y_0;
	results.sigma_x = sigma_x0;
	results.sigma_y = sigma_y0;
	results.a = a_0;
	results.b = b_0;
	results.c = c_0;	
	
	/* COSTRUZIONE DELL'IMMAGINE */
	for (i=0;i<length;i++){
		for(j=0;j<width;j++){
			temp = (int) evaluateGaussian(&results,j,i);
			//printf("%d\n",temp);
			matrix[i][j] = temp;
		}
	}
	
	/* WRITING THE IMAGE TO BE FITTED ON A TIFF FILE */
	writeImage((unsigned char *)matrix,(char *) OUTPUT_MATRIX, width, length);
	
	maxmin( (unsigned char*) matrix, width, length, &max, &min);
	
	printf("MAX: %d MIN: %d\n", max, min);
	
	/* a pixel mask is created in order to reduce the dimensione of the region to analyze with the centroid */
	unsigned char *mask = createMask( (unsigned char*) matrix, width, length, max, min, CROP_PARAMETER);
	
#if DEBUG
	writeImage(mask, (char *) "mask.tiff", width, length);
#endif
	
	centroid(mask, width, length, &x0, &y0, &FWHM_x, &FWHM_y);
	
#if DEBUG
	printf("centro in %f - %f\nCon ampiezza %f e %f\n", x0, y0, FWHM_x, FWHM_y);
#endif
	
	delete mask;
	
	/* inizialization for the diameter of the gaussian*/
	span_x = (int) (2 * FWHM_x);
	span_y = (int) (2 * FWHM_y);
	
	/* determination of the dimension of the crop */
	dimx = 2 * span_x + 1;
	dimy = 2 * span_y + 1;
	
	/* inizialization of the position coordinates */
	x = (int) x0;
	y = (int) y0;
	
	/**
	 inizialization of the test_g struct.
	 NOTE: the coordinates of the position (x,y) are relative to the cropped portion of the image.
	 the value of span_x, which is approximately the diameter of the gaussian, is generally not as bad
	 as you may think to start the fit. 
	 */
	test_g.A = max;
	test_g.x_0 = span_x;
	test_g.y_0 = span_y;
	test_g.sigma_x = FWHM_x;
	test_g.sigma_y = FWHM_y;
	test_g.a = 0;
	test_g.b = 0;
	test_g.c = min;
	
	fprintf(risultati, "%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\n", (&test_g)->A, (&test_g)->x_0 + x - span_x, (&test_g)->y_0 + y - span_y, (&test_g)->sigma_x, (&test_g)->sigma_y, (&test_g)->a, (&test_g)->b, (&test_g)->c);
	
	
	/* THIS PART CAN BE ITERATIVE */
	
	unsigned char *cropped = cropImage((unsigned char*) matrix, width, length, x - span_x, x + span_x, y - span_y, y + span_y);
	
#if DEBUG
	writeImage(cropped, (char *) "./CROP.tiff", dimx, dimy);
#endif
	
	for(i=0;i<ITERATION;i++){
		
		/* FIT FUNCTION */
		iteration(cropped, dimx, dimy, &test_g);
		
		fprintf(risultati, "%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\n", (&test_g)->A, (&test_g)->x_0 + x - span_x, (&test_g)->y_0 + y - span_y, (&test_g)->sigma_x, (&test_g)->sigma_y, (&test_g)->a, (&test_g)->b, (&test_g)->c);
	}
	return 0;
}
Beispiel #19
0
void ImageBitmap::notifyImageSourceChanged()
{
    m_bitmap = cropImage(m_imageElement->cachedImage()->image(), m_cropRect);
    m_bitmapOffset = IntPoint();
    m_imageElement = nullptr;
}
Beispiel #20
0
int main (int argc, char** argv)
{
	// for storing results of argument processing
	// general
	bool displayInfo = true;
	char* inFileName = "";

	// threshold filter
	bool runThreshold = false;
	float threshold = THRESH_ERROR;

	// crop
	bool runCrop = false;
	int cropWidth = CROP_DIM_ERROR;
	int cropHeight = CROP_DIM_ERROR;
	int cropStart[] = {0,0};

	// resize
	bool runResize = false;
	float scaling = SCALING_ERROR;
	char* resType = "";

	// default output file name
	char* outFileName = "out.bmp";
	
	// process arguments, checking for errors
	if (processArguments(argc, argv, &runThreshold, &runCrop, &runResize, 
		&displayInfo, &inFileName, &outFileName, &threshold, &cropWidth, 
		&cropHeight, cropStart, &scaling, &resType) != EXIT_SUCCESS)
	{
		fprintf(stderr, "Unable to process arguments.\n");
		return EXIT_FAILURE;
	}

	// open the file
	FILE *inFile = fopen(inFileName, "r");

	// check that file opened okay
	if (inFile == NULL)
	{
		fprintf(stderr, "Unable to open file: %s\n", inFileName);
		return EXIT_FAILURE;
	}

	// read in the file header and check that it went okay
	struct bmpFileHeader *fileHead = getFileHeader(inFile);

	if (fileHead == NULL)
	{
		fprintf(stderr, "Unable to set up file header.\n");
		return EXIT_FAILURE;
	}

	struct bmpInfoHeader *infoHead = getInfoHeader(inFile);

	if (infoHead == NULL)
	{
		fprintf(stderr, "Unable to set up info header.\n");
		return EXIT_FAILURE;
	}

	// check the format of the file
	if (formatCheck(fileHead, infoHead) != EXIT_SUCCESS)
	{
		fprintf(stderr, "Program cannot handle this format.\n");
		return EXIT_FAILURE;
	}


	// if we're displaying info, do so
	if (displayInfo)
	{
		// print out header information
		printInfo(fileHead, infoHead);
	}

	// move file pointer on to start of image, if necessary
	if (fileHead->offset != (sizeof(struct bmpFileHeader) + 
		sizeof(struct bmpInfoHeader)))
	{
		fseek(inFile, 
			((int)fileHead->offset - (sizeof(struct bmpFileHeader) + 
				sizeof(struct bmpInfoHeader))), SEEK_CUR);
	}

	// if we're running a threshold filter, do so
	if (runThreshold)
	{
		// apply threshold filter to image, checking for errors
		if (applyThreshold(inFile, fileHead, infoHead, outFileName, threshold) 
			== EXIT_FAILURE)
		{
			fprintf(stderr, "Unable to apply threshold.\n");
			return EXIT_FAILURE;
		}
	}

	// if we're cropping the image, do so
	if (runCrop)
	{
		// crop the image, checking for errors
		if (cropImage(inFile, fileHead, infoHead, outFileName, cropWidth,
			cropHeight, cropStart) == EXIT_FAILURE)
		{
			fprintf(stderr, "Unable to crop image.\n");
			return EXIT_FAILURE;
		}
	}

	// if we're resizing the image do so
	if (runResize)
	{
		// resize image checking for errors
		if (resizeImage(inFile, fileHead, infoHead, outFileName, scaling, resType) 
			== EXIT_FAILURE)
		{
			fprintf(stderr, "Unable to resize image.\n");
			return EXIT_FAILURE;
		}
	}

	// free up allocated memory
	free(infoHead);
	free(fileHead);

	// close input file, checking for errors
	if (fclose(inFile) != 0)
	{
		fprintf(stderr, "Unable to close input file.\n");
		return EXIT_FAILURE;
	}

	return EXIT_SUCCESS;
}
Beispiel #21
0
cv::Mat cropImage(cv::Mat mat, vss::Point p1, vss::Point p2) {
    cv::Rect rect = cv::Rect(cv::Point((int)p1.x, (int)p1.y),
                             cv::Point((int)p2.x, (int)p2.y));

    return cropImage(mat, rect);
}
void OpenCVPicture::randomCrop(RNG &rng, int subsetSize) {
  assert(subsetSize <= std::min(mat.rows, mat.cols));
  cropImage(mat, rng.randint(mat.cols - subsetSize),
            rng.randint(mat.rows - subsetSize), subsetSize, subsetSize);
  xOffset = yOffset = -subsetSize / 2;
}
Beispiel #23
0
void ProfilePictureWindow::finishedSelection()
{
    QMaemo5InformationBox::information(this,"Processing image");

    QTimer::singleShot(100,this,SLOT(cropImage()));
}
void ImageTransformation::writeImages(vector<coordinateInfo> coordinates, Mat imageBase, QString destinationPath, QString fileName, QString extension, MainWindow* mainW)
{

    ///Crop the interest area
    for (uint j=0; j < coordinates.size(); j++)
    {
        QString number = "_" + QString::number(j);

        Mat imageRotate0;
        Mat imageRotate90;
        Mat imageRotate180;
        Mat imageRotate270;

        Mat imageTemp;
        imageBase.copyTo(imageTemp);

        if (mainW->bResizeChecked)
        {
            int iWidth = mainW->iWidth;
            int iHeight = mainW->iHeight;
            resize(imageTemp,imageTemp,Size(iWidth,iHeight), 0, 0, INTER_CUBIC);

            imwrite((destinationPath + "/" + resizesPath + fileName + extension).toStdString(), imageTemp );

            LogImgDataset::getInstance().Log(INFO, "Resize image");
        }

        if (mainW->bCropChecked)
        {

            if (mainW->iWindowSize < imageTemp.cols && mainW->iWindowSize < imageTemp.rows)
            {
                if ( coordinates[j].x <= imageTemp.cols && coordinates[j].y <= imageTemp.rows)
                {
                    //Recorte da imagem a partir dos dados dos CSVs
                    QString number = "_" + QString::number(j);
                    Mat imageCrop = cropImage(imageBase, Point(coordinates[j].x,coordinates[j].y), cv::Size(mainW->iWindowSize,mainW->iWindowSize), mainW->iOffset);
                    imwrite((destinationPath + "/" + cropPath + fileName + number + extension).toStdString(), imageCrop);
                    imageTemp = imageCrop;

                    LogImgDataset::getInstance().Log(INFO, "Crop image");
                } else
                {
                    LogImgDataset::getInstance().Log(ERROR, "Crop image failed");
                    LogImgDataset::getInstance().Log(ERROR, "The crop is out of range of the image");
                }
            } else
            {
                LogImgDataset::getInstance().Log(ERROR, "Crop image failed");
                LogImgDataset::getInstance().Log(ERROR, "The window size is bigger than image size.");
            }

        }

        if (mainW->bRotateChecked)
        {
            //Rotate Images 0 - 90 - 180 -270
            imageRotate0 = imageTemp;
            imageRotate90 = rotateImage(imageTemp, 90.0);
            imageRotate180 = rotateImage(imageTemp, 180.0);
            imageRotate270 = rotateImage(imageTemp, 270.0);

            imwrite((destinationPath + "/" + rotateImagesPath + fileName + number + extension).toStdString(), imageRotate0 );
            imwrite((destinationPath + "/" + rotateImagesPath +  fileName + number + "_R90" + extension).toStdString(), imageRotate90 );
            imwrite((destinationPath + "/" + rotateImagesPath +  fileName + number + "_R180" + extension).toStdString(), imageRotate180 );
            imwrite((destinationPath + "/" + rotateImagesPath +  fileName + number + "_R270" + extension).toStdString(), imageRotate270 );

            LogImgDataset::getInstance().Log(INFO, "Rotate images: 0 - 90 - 180 - 270");

            if (mainW->bFlipChecked)
            {
                //Vertical Flip in Rotate Images
                Mat imageFlipV0 = flipImage(imageRotate0, 1);
                Mat imageFlipV90 = flipImage(imageRotate90, 1);
                Mat imageFlipV180 = flipImage(imageRotate180, 1);
                Mat imageFlipV270 = flipImage(imageRotate270, 1);

                imwrite((destinationPath + "/" + rotateImagesPath +  fileName + number + "_F0" + extension).toStdString(), imageFlipV0 );
                imwrite((destinationPath + "/" + rotateImagesPath +  fileName + number + "_F90" + extension).toStdString(), imageFlipV90 );
                imwrite((destinationPath + "/" + rotateImagesPath +  fileName + number + "_F180" + extension).toStdString(), imageFlipV180 );
                imwrite((destinationPath + "/" + rotateImagesPath +  fileName + number + "_F270" + extension).toStdString(), imageFlipV270 );

                LogImgDataset::getInstance().Log(INFO, "Fliping ...");
            }

        }
        else if (mainW->bFlipChecked)
        {
            //Vertical Flip in Rotate Images
            Mat imageFlipV0 = flipImage(imageRotate0, 1);
            imwrite((destinationPath + "/" + rotateImagesPath +  fileName + number + "_F0" + extension).toStdString(), imageFlipV0 );

            LogImgDataset::getInstance().Log(INFO, "Fliping ...");

        }

    }
}
Beispiel #25
0
int main(int argc, char *argv[])
{
  image myPic;
  imageInfo picInfo;
  int count;
  char *outputType = NULL;
  int err;
  int aCrop = NO;
  int left = -1, right = -1, top = -1, bottom = -1;
  double xscale = 1, yscale = 1;
  double xs2, ys2;
  int xdim = 0, ydim = 0;
  int ditherMode = ' ';
  int mMono = NO;
  int outType = NO;
  int scaletofit = NO;
  int numBits = 1;
  char *outFile = NULL;
  char *type = NULL, *ext = NULL;
  char *p;
  int nv;
  double darken = 0;
  double contrast = 0;
  double rotate = 0;
  struct stat sbuf;
  int blend = NO;
  static char filename[MAXPATHLEN + 1] = "";
  int negative = NO;
  int enhance = NO;
  formatInfo fInfo;
  

  count = getargs(argc, argv, "nbosabLiRiTiBixdydXiYidcmbpbsbbiDdSbKdfseird",
		   &negative, &outputType, &aCrop, &left, &right, &top,
		   &bottom, &xscale, &yscale, &xdim, &ydim, &ditherMode,
		   &mMono, &outType, &scaletofit, &numBits, &darken,
		   &blend, &contrast, &outFile, &enhance, &rotate
		   );

  if (count < 0 || count == argc) {
    if (count < 0 && -count != '-')
      fprintf(stderr, "Bad flag: %c\n", -count);
    fprintf(stderr, "Usage: %s [-options] filename\n"
	     "  options:\n"
	     "\tn: make negative\n"
	     "\to: string indicating output format\n"
	     "\ta: auto crop non plotting areas\n"
	     "\tL, R, T, B: specify where to crop picture\n"
	     "\tx, y: specify scale factor in that direction\n"
	     "\tX, Y: specify dimension of picture in that direction\n"
	     "\td: select dither method: (D)ither, (T)hreshold, or (H)alftone\n"
	     "\tm: convert image to monochrome\n"
	     "\tp: dither image for output to printer\n"
	     "\ts: scale image to fill up specified screen\n"
	     "\tb: number of bits to dither to\n"
	     "\tD: how much to brighten image\n"
	     "\tK: contrast level\n"
	     "\tS: blend pixels together when scaling\n"
	     "\tf: file name to save to\n"
	     "\te: contrast for enhance image\n"
	     "\tr: number of degrees to rotate\n"
	     , *argv);
    exit(1);
  }

  for (; count < argc; count++) {
    if ((err = load_pic(argv[count], &myPic))) {
      fprintf(stderr, "Cannot load file %s\nError: %s\n", argv[count], picErrorStr(err));
      exit(1);
    }
    
    if (!getImageInfo(argv[count], &picInfo))
      type = picInfo.extension;

    if (!outputType) 
      outputType =  type;

    if (!infoForFormat(outputType, &fInfo)) {
      ext = fInfo.extension;
      if (scaletofit && !xdim && !ydim && fInfo.maxWidth && fInfo.maxHeight) {
	xdim = fInfo.maxWidth;
	ydim = fInfo.maxHeight;
      }
    }
    
    if (mMono)
      makeMono(&myPic);
    
    if (left >= 0 || right >= 0 || top >= 0 || bottom >= 0) {
      if (left < 0)
	left = 0;
      if (right < 0)
	right = myPic.width - 1;
      if (top < 0)
	top = 0;
      if (bottom < 0)
	bottom = myPic.height - 1;
      cropImage(left, top, right, bottom, &myPic);
    }
    
    if (aCrop)
      autoCropImage(&myPic, 40);

    if (rotate)
      rotateImage(&myPic, (rotate * -3.141592) / 180.0);
    
    xs2 = xscale;
    ys2 = yscale;
    if (scaletofit) {
      if (!ydim && xdim) {
	xs2 = (double) xdim / ((double) myPic.width * xscale) * xscale;
	ys2 = ((double) xdim / ((double) myPic.width * xscale)) * yscale;
      }
      else if (ydim) {
	xs2 = ((double) ydim / ((double) myPic.height * yscale)) * xscale;
	ys2 = (double) ydim / ((double) myPic.height * yscale) * yscale;
	if (xdim && (myPic.width * xs2) > xdim) {
	  xs2 = (double) xdim / ((double) myPic.width * xscale) * xscale;
	  ys2 = ((double) xdim / ((double) myPic.width * xscale)) * yscale;
	}
      }
    }
    else {
      if (xdim)
	xs2 = (double) xdim / (double) myPic.width;
      if (ydim)
	ys2 = (double) ydim / (double) myPic.height;
    }
    xscale = xs2;
    yscale = ys2;

    scaleImage(xscale, yscale, blend, &myPic);

    if (darken || contrast)
      adjustImage(&myPic, contrast, darken);
    if (enhance) {
      makeMono(&myPic);
      enhanceImage(&myPic, enhance);
    }
    
    handle_dithering(ditherMode, &myPic, outType, numBits);
    if (negative)
      negateImage(&myPic);

    if (outFile) {
      strcpy(filename, outFile);
      if (!stat(filename, &sbuf) && (sbuf.st_mode & S_IFDIR)) {
	if (filename[strlen(filename) - 1] != '/')
	  strcat(filename, "/");
	if ((p = strrchr(argv[count], '/')))
	  strcat(filename, p + 1);
	else
	  strcat(filename, argv[count]);
      }
    }
    else
      strcpy(filename, argv[count]);
    
    p = change_extension(filename, type, ext, 0);
    nv = 2;
    while (!stat(p, &sbuf)) {
      p = change_extension(filename, type, ext, nv);
      nv++;
    }

    if ((err = save_pic(p, outputType, &myPic))) {
      fprintf(stderr, "Cannot save file %s\nError: %s\n", p, picErrorStr(err));
      exit(1);
    }

    fprintf(stderr, "Saved %s as %s\n", argv[count], p);

    freeImage(&myPic);
  }

  exit(0);
  return 0;
}