Beispiel #1
0
void PhotoDetails::slotRotate270() {

    if (RadioButton_270->isChecked()) {
        RadioButton_90->setChecked(false);
        RadioButton_180->setChecked(false);
        emit rotateImage(270);
    } else {
        RadioButton_270->setChecked(false);
        emit rotateImage(0);
    }

}
Beispiel #2
0
void QNode::incoming_image(const sensor_msgs::ImageConstPtr& msg) {
    // Convert ROS images to OpenCV images
    cv_bridge::CvImagePtr cv_ptr;
    try {
        cv_ptr = cv_bridge::toCvCopy(msg,enc::MONO8);// enc::BGR8);
    } catch (cv_bridge::Exception& e) {
        ROS_ERROR_STREAM(e.what());
        return;
    }
    //cv_ptr->image;

    //TODO Operate on CV Image
    const double rotX = nav_last.rotX;

    if (rollcomp)
        cv_ptr->image =  rotateImage(cv_ptr->image, rotX*-1);

    std::vector<cv::Rect> found;
    hog.detectMultiScale(cv_ptr->image, found);
    for(unsigned i = 0; i < found.size(); i++) {
        cv::Rect r = found[i];
        rectangle(cv_ptr->image, r.tl(), r.br(), cv::Scalar(0,255,0), 2);
    }
    cv::waitKey(5);


    //TODO Publish image
    pub_image.publish(cv_ptr->toImageMsg());
}
Beispiel #3
0
void Balloon::drawBalloons(Mat image)
{
	Rect bound;

	vector<ImageToMove>::iterator balloon;
	for (balloon = _balloonList.begin(); balloon < _balloonList.end(); balloon++) {
		bound = Rect(balloon->position.x, 
					balloon->position.y, 
					_imageList[balloon->imageIndex].size().width, 
					_imageList[balloon->imageIndex].size().height);
//		add(image(bound), balloon->image, image(bound), balloon->alphaChannel);
//		cout << bound.x << " " << bound.y << " " << bound.width << " " << bound.height << endl;
//		cout << _image.cols << " " << _image.rows << endl;
		//imshow("bound", image(bound));
	
		Mat rotatedImage = rotateImage(_imageList[balloon->imageIndex], balloon->velocityAngle - 90);
		Mat rotatedAlphaChannel = rotateImage(_alphaChannelList[balloon->imageIndex], balloon->velocityAngle - 90);
		
		rotatedImage.copyTo(image(bound), rotatedAlphaChannel);
	}
}
Beispiel #4
0
void PhotoDetails::slotCancel() {

    if (modifiedurl) {
        m_photo.first()->fileurl=oldfileurl;
        emit updatePreview(m_photo.first());
    }

    emit rotateImage(m_photo.first()->rotate);
    updateImageInfo();


}
int main()
{
         
          IplImage* img;
          IplImage* rotated_img;

          int angle=0;
          int zoom=24;
         
          //creating the window with 2 track bars
          cvNamedWindow("MyWindow");
          cvCreateTrackbar("Angle", "MyWindow", &angle, 360, 0);
          cvCreateTrackbar("Zoom", "MyWindow", &zoom, 99, 0);
         
          while(true){
              //load the original image
              img = cvLoadImage("NS2.jpg");
             
              //rotate the image
              rotated_img=rotateImage( img, angle, (zoom+1)/25.0 );

              //display the rotated image
              cvShowImage("MyWindow", rotated_img);

              //clean up
              cvReleaseImage(&img);
              cvReleaseImage(&rotated_img);
             
              //if user press 'ESC' button, program quit the while loop
              int c=cvWaitKey(50);              
              if(c==27) break;
          }
         
         
          cvDestroyWindow("MyWindow");
         
          return 0;
}
Beispiel #6
0
bool SlideEventHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&)
{
    switch(ea.getEventType())
    {
    case(osgGA::GUIEventAdapter::KEYDOWN):
    {
        if (ea.getKey()=='a')
        {
            _autoSteppingActive = !_autoSteppingActive;
            _previousTime = ea.getTime();
            return true;
        }
        else if ((ea.getKey()=='n') || (ea.getKey()==osgGA::GUIEventAdapter::KEY_Right))
        {
            nextSlide();
            return true;
        }
        else if ((ea.getKey()=='p') || (ea.getKey()==osgGA::GUIEventAdapter::KEY_Left))
        {
            previousSlide();
            return true;
        }
        else if ((ea.getKey()=='w') || (ea.getKey()==osgGA::GUIEventAdapter::KEY_KP_Add))
        {
            scaleImage(0.99f);
            return true;
        }
        else if ((ea.getKey()=='s') || (ea.getKey()==osgGA::GUIEventAdapter::KEY_KP_Subtract))
        {
            scaleImage(1.01f);
            return true;
        }
        else if (ea.getKey()=='j')
        {
            offsetImage(-0.001f,0.0f);
            return true;
        }
        else if (ea.getKey()=='k')
        {
            offsetImage(0.001f,0.0f);
            return true;
        }
        else if (ea.getKey()=='i')
        {
            offsetImage(0.0f,-0.001f);
            return true;
        }
        else if (ea.getKey()=='m')
        {
            offsetImage(0.0f,0.001f);
            return true;
        }
        else if (ea.getKey()==' ')
        {
            initTexMatrices();
            return true;
        }
        return false;
    }
    case(osgGA::GUIEventAdapter::DRAG):
    case(osgGA::GUIEventAdapter::MOVE):
    {
        static float px = ea.getXnormalized();
        static float py = ea.getYnormalized();

        float dx = ea.getXnormalized()-px;
        float dy = ea.getYnormalized()-py;

        px = ea.getXnormalized();
        py = ea.getYnormalized();

        rotateImage(dx,dy);

        return true;
    }

    default:
        return false;
    }
}
Beispiel #7
0
// Main function
int main( void )
{
  char command[MAXLENGTH];
  char c;


 /********************************************************************
  * YOU WILL NEED TO COMPLETE THE FOLLOWING SECTION FOR STAGES 2 - 5 *
  *******************************************************************/

  printPrompt();

  while( fgets( command, MAXLENGTH, stdin ) != NULL ) 
  {

    int  imgNum;
    char *p;

    if(( p=strrchr( command, '\n')) != NULL ) {
      *p = '\0'; // remove '\n' at end of line
    }
    // find the first non-space character in the command
    p = command;
    while(isspace(*p)) {
      p++;
    }
    c = tolower(*p);

    if( isdigit(c)) // Command k
    {
       if( sscanf( command, "%d", &imgNum ) == 1 ) 
       {
           //Checks to see if there's images in the album.     
           if(first != NULL)
           {
               //Retrieves the image.
               found = getCurrentImage(first);
               found2 = selectImage(found, imgNum);

               //Checks to see if the requested image exist in the album.
               if(found2 != NULL)
               {
                   found->current = FALSE;
                   found2->current = TRUE;
                   printNodeInfos(found2); 
                   last_action = 'k';
                   location = found->index; //Index of the previous image 
                   found = NULL;
                   found2 = NULL;
                   
               }
           }
       }
    }
    else switch( c ) 
    {

    case 'h': // help

      printf(" A - Add image\n" );
      printf(" I - Index\n" );
      printf(" P - Print image\n" );
      printf(" F - Forward\n" );
      printf(" B - Back\n" );
      printf("<k>- make image number k the current image\n");
      printf(" D - Delete image\n" );
      printf(" L - Look for image\n" );
      printf(" R - Rotate image counterclockwise\n" );
      printf(" M - Mirror image (reflect vertically)\n" );
      printf("NE - zoom into North East corner\n" );
      printf("NW - zoom into North West corner\n" );
      printf("SW - zoom into South West corner\n" );
      printf("SE - zoom into South East corner\n" );
      printf(" O - zoom Out\n" );
      printf(" U - Undo\n" );
      printf(" H - Help\n" );
      printf(" Q - Quit\n" );
      break;

      // INSERT CODE FOR OTHER COMMANDS
    
    case 'a':
        p++; //Moves cursor away from 'a'
        while(isspace(*p)) 
        {
             p++;
        }
        int *dim;
        QTnode* qt = getImage(p, dim);

        if(qt != NULL)
        {
            insertNode(qt, dim, p);
            printNodeInfos(getCurrentImage(first)); //Whenever a node is added, it becomes the selected node
        }
        last_action = 'a';
        break;
    
    case 'i':
        if(first != NULL)
        {
            printIndex(first);
        }
        break;
        
    case 'p':
    {
        ListNode* currentImage = getCurrentImage(first);
        
        if(currentImage != NULL)
        {
            printImage(currentImage->image, currentImage->size);
        }
        
        break;
    }
        
    case 'f':
    {
        ListNode* currentImage = getCurrentImage(first);
        
        if(currentImage != NULL && (currentImage->next != NULL))
        {
            
            currentImage->current = FALSE;
            currentImage = currentImage->next;
            currentImage->current = TRUE;
            printNodeInfos(currentImage);
            last_action = 'f';
        }
        break;
    }
        
    case 'b':
    {
        ListNode* currentImage = getCurrentImage(first);
        
        if(currentImage != NULL && (currentImage->previous != NULL))
        {
            currentImage->current = FALSE;
            currentImage = currentImage->previous;
            currentImage->current = TRUE;
            printNodeInfos(currentImage);
            last_action = 'b';
        }
        break;
    } 
   
        //'K' command is treated in the upper portion of the code
        
    case 'd':
        removeNode();
        if(first != NULL)
        {
            printNodeInfos(getCurrentImage(first)); 
        }    
        last_action = 'd';
         
        break;
        
    case 'l':
        if(first != NULL)
        {
            p++; //Moves cursor away from 'a'
            while(isspace(*p)) 
            {
                 p++;
            }
            ListNode* foundImage = findBySubString(first, p);
            
            //Image with the substring was found
            if(foundImage != NULL)
            {
                ListNode* currentImage = getCurrentImage(first);               
                currentImage->current = FALSE;
                foundImage->current = TRUE;
                printNodeInfos(getCurrentImage(first));
                last_action = 'l';
                location = currentImage->index;
            }   
        }
        break;
        
        case 'r':
        {
            ListNode* currentImage = getCurrentImage(first);
            if(currentImage != NULL)
            {
                rotateImage(currentImage->image);
                printImage(currentImage->image, currentImage->size); 
            } 
            last_action = 'r';           
            break;
        }
        
        case 'm':
        {
            ListNode* currentImage = getCurrentImage(first);
            if(currentImage != NULL)
            {
                mirrorImage(currentImage->image);
                printImage(currentImage->image, currentImage->size);
            }
            last_action = 'm';
            
            break;
        }
        
        case 'n':
        {
            ListNode* currentImage = getCurrentImage(first);
            if(currentImage == NULL)
            {
                break;
            }
            
            //This line gets the next character of the command, so it can be
            //treated accordingly.
            char c2 = *(++p); //Dereferencing the pointer and moving it to the next char of the string
            
            if(c2 == 'e')
            {
                if(currentImage->image->ne == NULL)
                {
                    break;
                }
                
                currentImage->image = currentImage->image->ne;
                printImage(currentImage->image, currentImage->size);
                last_action = 'w';  //because "ne" does not work, find a letter that is not used
                location = 'w';
            }
            
            else if(c2 == 'w')

            {
                if(currentImage->image->nw == NULL)
                {
                    break;
                }
                
                currentImage->image = currentImage->image->nw;
                printImage(currentImage->image, currentImage->size);
                last_action = 'x';
                location = 'x';
            }
            
            break;
        }
        
        case 's':
        {
            ListNode* currentImage = getCurrentImage(first);
            
            if(currentImage == NULL)
            {
                break;
            }
            
            //This line gets the next character of the command, so it can be
            //treated accordingly.
            char c2 = *(++p); //Dereferencing the pointer and moving it to the next char of the string
            
            if(c2 == 'e')
            {
                if(currentImage->image->se == NULL)
                {
                    break;
                }
                
                currentImage->image = currentImage->image->se;
                printImage(currentImage->image, currentImage->size);
                last_action = 'y';
                location = 'y';
            }
            
            else if(c2 == 'w')
            {
                if(currentImage->image->sw == NULL)
                {
                    break;
                }
                
                currentImage->image = currentImage->image->sw;
                printImage(currentImage->image, currentImage->size);
                last_action = 'z';
                location = 'z';
            }
            break;
        }
        
        case 'o':
        {
            ListNode* currentImage = getCurrentImage(first);
            
            if(currentImage == NULL || (currentImage->image->out == NULL))
            {
                break;
            }
            
            currentImage->image = currentImage->image->out;
            printImage(currentImage->image, currentImage->size);
            last_action = 'o';
            break;
        }
        
         case 'u':
 
    if(last_action == 'm'){
    ListNode* currentImage = getCurrentImage(first);
            if(currentImage != NULL)
            {
                mirrorImage(currentImage->image);
                printImage(currentImage->image, currentImage->size);
            }
            
            break;
        }
 
    else if(last_action == 'r'){
   ListNode* currentImage = getCurrentImage(first);
            if(currentImage != NULL)
            {
                rotateImage(currentImage->image);
                rotateImage(currentImage->image);
                rotateImage(currentImage->image);
                printImage(currentImage->image, currentImage->size); 
      break;        } 
   }
  
  else if(last_action == 'a'){
  removeNode();
        if(first != NULL)
        {
            printNodeInfos(getCurrentImage(first)); 
        }    
  break;
  }
   
  else if(last_action == 'd'){
	//todo me no smart
        break;
  }
  
  else if(last_action == 'w' || (last_action == 'x') || (last_action == 'y') || (last_action == 'z')){
  
            ListNode* currentImage = getCurrentImage(first);
            
            if(currentImage == NULL || (currentImage->image->out == NULL))
            {
                break;
            }
            
            currentImage->image = currentImage->image->out;
            printImage(currentImage->image, currentImage->size);
            break;
  }
  
  else if(last_action == 'o'){
  ListNode* currentImage = getCurrentImage(first);
  
		  if(location == 'w')
		  { if(currentImage->image->ne == NULL)
                {
                    break;
                }
                
                currentImage->image = currentImage->image->ne;
                printImage(currentImage->image, currentImage->size);
		   
		  	break;
		  }
   
		 else if(location == 'x')
		 {                if(currentImage->image->nw == NULL)
                {
                    break;
                }
                
                currentImage->image = currentImage->image->nw;
                printImage(currentImage->image, currentImage->size);
		     break;
		 }
   
		 else if(location == 'y')
		 { if(currentImage->image->se == NULL)
                {
                    break;
                }
                
                currentImage->image = currentImage->image->se;
                printImage(currentImage->image, currentImage->size);
		 	break;
		 }
   
	   else if(location == 'z')
	   { if(currentImage->image->sw == NULL)
                {
                    break;
                }
                
                currentImage->image = currentImage->image->sw;
                printImage(currentImage->image, currentImage->size);
			break;
	   }
   
   }
   
 else if(last_action == 'b'){
         ListNode* currentImage = getCurrentImage(first);
        
        if(currentImage != NULL && (currentImage->next != NULL))
        {
            
            currentImage->current = FALSE;
            currentImage = currentImage->next;
            currentImage->current = TRUE;
            printNodeInfos(currentImage);
        }
 break;
 }
 
 else if(last_action == 'f'){
 ListNode* currentImage = getCurrentImage(first);
        
        if(currentImage != NULL && (currentImage->previous != NULL))
        {
            currentImage->current = FALSE;
            currentImage = currentImage->previous;
            currentImage->current = TRUE;
            printNodeInfos(currentImage);
        }
 break;
 }
 
 else if(last_action == 'k' || (last_action == 'l')){
                //Retrieves the image.
               found = getCurrentImage(first);
               found2 = selectImage(found, location);

               //Checks to see if the requested image exist in the album.
               if(found2 != NULL)
               {
                   found->current = FALSE;
                   found2->current = TRUE;
                   printNodeInfos(found2); 
                   found = NULL;
                   found2 = NULL;
                   
               }
 break;
 }
 
   

        
    case 'q': // quit program
      printf("Bye!\n");
      return 0;
      break;
      
    default:
      printf("Unrecognized command: %s\n", command );
      break;
    }

    printPrompt();
  }

  return 0;
}
  pair<Strip, Strip> cutstrips(Mat *left_image, 
  			     Mat *right_image, 
  			     Point2f epipole_left, 
   			     Point2f epipole_right, 
  			     Mat epipolar_line, 
  			     Point2f direction_point,
  			     double bandwidth) { 
  	Mat strip1, strip2, mask1, mask2;
  	Mat hline = (Mat_<float>(3, 1) << 0, 1, 0); 
  	pair<Size, Size> sizes = 
  		pair<Size, Size>((*left_image).size(),
  			         (*right_image).size());
  	pair<Point2f, Point2f> centers = 
      		pair<Point2f, Point2f>(
  		 Point2f(sizes.first.width/2,
  			 sizes.first.height/2), 
  		 Point2f(sizes.second.width/2, 
  			 sizes.second.height/2));
  	pair<double, double>   angles = 
  		get_angles(epipole_left, 
  			   direction_point, 
  			   epipolar_line, 
  			   hline);
  	pair<Point2f, Point2f> shifts = 
  		pair<Point2f, Point2f>(
  		 get_rotation_shift(sizes.first.width, 
  				    sizes.first.height, 
  				    angles.first), 
  		 get_rotation_shift(sizes.second.width, 
  				    sizes.second.height, 
  				    angles.second));

  	Point2f new_epipole_left = 
  		rotatePoint(epipole_left, 
  			    angles.first, 
  			    centers.first) +  shifts.first;
  	Point2f new_epipole_right = 
  		rotatePoint(epipole_right, 
  			    angles.second, 
  			    centers.second) + shifts.second;

  	pair<Rect, Rect> bounds = 
  		get_cut_bounds(bandwidth, 
  			       pair<Point2f, Point2f>(
  				new_epipole_left, 
  			   	new_epipole_right));
  	pair<Point2f, Point2f> rshifts = 
  		pair<Point2f, Point2f>(
  		 new_epipole_left - epipole_left 
  		  - Point2f(0, bounds.first.y),
  		 new_epipole_right - epipole_right 
  		  - Point2f(0, bounds.second.y));


  	mask1 = Mat::ones(sizes.first, CV_8U);
  	mask2 = Mat::ones(sizes.first, CV_8U);

  	init_mat_with_border(&mask1, 10, 10);
  	init_mat_with_border(&mask2, 10, 10);

  	strip1 = rotateImage(*left_image, 
  			     -angles.first, 
  			     true, false, 
  			     bounds.first.y, 
  			     bounds.first.height);
  	strip2 = rotateImage(*right_image, 
  			     -angles.second, 
  			     true, false, 
  			     bounds.second.y, 
  			     bounds.second.height);
  	mask1  = rotateImage(mask1, 
  			     -angles.first, 
  			     true, false, 
  			     bounds.first.y, 
  			     bounds.first.height);
  	mask2  = rotateImage(mask2, 
  			     -angles.second, 
  			     true, false, 
  			     bounds.second.y, 
   	 		     bounds.second.height);


  	return pair<Strip, Strip>(
  		Strip(strip1, 
  		      mask1, 
  		      angles.first,  
  		      rshifts.first), 
  		Strip(strip2, 
  		      mask2, 
  		      angles.second,
  		      rshifts.second));
  }
Beispiel #9
0
void Scene::rotateHalf() {
  emit rotateImage(2);
}
Beispiel #10
0
void Scene::rotateCCW() {
  emit rotateImage(3);
}
Beispiel #11
0
void ModelMaker::extractModel(cv::Mat origframe)
{
    //       qDebug()<<"Frame is"<<frame.empty();
    for(int i = 0; i < centroids.size(); i++) {
        
        Mat subtractedframe(origframe);
        subtractedframe = subtractBack(origframe);
        Mat polymask = subtractedframe.clone();
        
        //                cv::cvtColor(frameMat, frameMat, CV_BGR2BGRA);
        
        //                cv::cvtColor(polymask, polymask, CV_BGR2BGRA);
        
        
        //cv::rectangle(mask, Point( 0, 0 ), Point( mask.cols, mask.rows), Scalar( 0, 255,0,255 ),-1, 8 ); //Fill all mask in
        
        polymask.setTo(Scalar(0,0,0,0));
        //Polgon Masking
        polygon = paintCanvas->polygons.at(i);
        
        Point poly_points[polygon.size()];
        
        //Find point furthest from center
        Point furthest = Point(paintCanvas->centerPoint.x()*xscale,paintCanvas->centerPoint.y()*yscale);  //set to center
        
        int scaledcenterx = paintCanvas->centerPoint.x()*xscale;
        int scaledcentery = paintCanvas->centerPoint.y()*yscale;
        int scaledheadx= paintCanvas->headPoint.x()*xscale;
        int scaledheady=paintCanvas->headPoint.y()*yscale;
        
        
        float biggestdistancesquared=0;
        
        
        for(int j=0;j<polygon.size();j++)
        {
            poly_points[j]=Point(xscale*polygon.at(j).x(), yscale*polygon.at(j).y());
            
            Point candidate = Point(xscale*polygon.at(j).x(), yscale*polygon.at(j).y());
            float distancecandidatesquared;
            //Find furthest
            distancecandidatesquared= (candidate.x - scaledcenterx)*(candidate.x - scaledcenterx) + (candidate.y - scaledcentery)*(candidate.y - scaledcentery);
            if(distancecandidatesquared>biggestdistancesquared){
                biggestdistancesquared=distancecandidatesquared;
                qDebug()<<"biggcandidate x "<<candidate.x <<"  y "<<candidate.y << "    distance ="<<biggestdistancesquared;
                
            }
            
            
            
        }
        
        const Point* ppt[1] = { poly_points };
        int npt[] = { polygon.size() };
        
        
        
        fillPoly( polymask,
                  ppt,
                  npt,
                  1,
                  Scalar( 255, 255,255,255 ),
                  
                  8,
                  0);
        
        
        
        //Debug
        //                                cv::circle(origframe,cv::Point(scaledcenterx,scaledcentery),1,Scalar(255,255,255,255),2);
        //                                cv::circle(origframe,cv::Point(scaledheadx,scaledheady),1,Scalar(255,0,255, 254),2);
        
        //cv::circle(polymask,cv::Point(scaledcenterx,scaledcentery),1,Scalar(255,255,255,255),2);
        //  cv::circle(polymask,cv::Point(scaledheadx,scaledheady),1,Scalar(255,0,255, 254),2);
        
        //  cv::circle(subtractedframe,cv::Point(scaledcenterx,scaledcentery),1,Scalar(255,255,255,255),2);
        //  cv::circle(subtractedframe,cv::Point(scaledheadx,scaledheady),1,Scalar(255,0,255, 254),2);
        
        
        
        //background subtraction: take original image, apply background as a mask, save over original
        //bitwise_and(subtractedframe, polymask, subtractedframe);
        
        qDebug()<<"Roi "<<x1<<"  "<<y1<<"  "<<x2<<"  "<<y2<<"  ";
        
        
        cv::cvtColor(polymask,polymask, CV_RGB2GRAY);
        
        
        //Full alpha mask = polygon selection (a =200) + BG subtracted organism (a= 255) + Center Mark ( a = 250) + head mark (a = 240)
        //Set Head to alpha=240
        //Set Center to Alpha = 250
        //Everything inside mask == alpha 200
        //Everything outside alpha=100;
        //BG subtracted ant = 255
        
        Mat maskedsubtraction;
        subtractedframe.copyTo(maskedsubtraction,polymask); // note that m.copyTo(m,mask) will have no masking effect
        cvtColor(maskedsubtraction, maskedsubtraction,CV_BGR2GRAY);
        polymask = polymask+155;   //255 moves to 255, 0 moves to 155
        polymask = polymask - 55;  //255 moves to 200, 155 moves to 100
        maskedsubtraction = polymask+maskedsubtraction;
        
        cv::circle(maskedsubtraction,cv::Point(scaledcenterx,scaledcentery),1,Scalar(250),2); //Encode the Center
        cv::circle(maskedsubtraction,cv::Point(scaledheadx,scaledheady),1,Scalar(240),2); //encode the head
        
        Mat bgr;
        bgr=origframe.clone();
        
        Mat alpha;
        maskedsubtraction.copyTo(alpha);
        Mat bgra;
        cvtColor(origframe, bgra,CV_BGR2BGRA); //Copy the origframe, we'll write over it next
        
        
        
        
        // forming array of matrices is quite efficient operations,
        // because the matrix data is not copied, only the headers
        Mat in[] = { bgr, alpha };
        // BGRa[0] -> bgr[0], BGRa[1] -> bgr[1],
        // BGRa[2] -> bgr[2], BGRa[3] -> alpha[0]
        int from_to[] = { 0,0,  1,1,  2,2,  3,3 };
        mixChannels( in, 2, &bgra, 1, from_to, 4 ); // input array, number of files in input array, destination, number of files in destination, from-to array, number of pairs in from-to
        
        
        
        QString ext = ".png";
        // QString fullframe = savepath+paintCanvas->polyNames.at(i)+"_"+QString::number(centroids[i].x())+"_"+QString::number(centroids[i].y())+"_"+QString::number(currentFrame)+ext;
        QString modelfilename = savepath+paintCanvas->polyNames.at(i)+"_f"+QString::number(currentFrame)+ext;
        
        //DEBUG IMAGES
        /*
              imwrite(modelfilename.toStdString()+"_subtraction",subtractedframe);
                imwrite(modelfilename.toStdString()+"_polymask",polymask);
                imwrite(modelfilename.toStdString()+"_alpha",alpha);
        */
        
        
        
        //save out Model
        
        //Full Keyframe
//        imwrite(modelfilename.toStdString()+"_keyframe",bgra); //Disabled for now
        
        qDebug()<<"Saved out: "<<modelfilename;
        
        //***Crop and Rotate ***//
        qDebug()<<"crop centered on  "<<scaledcenterx<<"  "<<scaledcentery;
        //crop the frame based on ROI
        Point2f src_center(scaledcenterx, scaledcentery);
        //To do this correctly use getRectSubPix instead of frameMat(MYROI) method
        // getRectSubPix only works with certain image formats (this is undocumented in opencv : P
        // so we have to do that cutting and mixing again!
        getRectSubPix(bgr, cv::Size(sqrt(biggestdistancesquared)*2,sqrt(biggestdistancesquared)*2), src_center, bgr);
        getRectSubPix(alpha, cv::Size(sqrt(biggestdistancesquared)*2,sqrt(biggestdistancesquared)*2), src_center, alpha);
        
        Mat bgracropped;
        cvtColor(bgr, bgracropped,CV_BGR2BGRA); //Copy the origframe, we'll write over it next
        Mat inagain[] = { bgr, alpha };
        int from_to2[] = { 0,0,  1,1,  2,2,  3,3 };
        
        //Note: the height and width dimensions have to be the same for the inputs and outputs
        mixChannels( inagain, 2, &bgracropped, 1, from_to2, 4 ); // input array, number of files in input array, destination, number of files in destination, from-to array, number of pairs in from-to
        
        
        //rotate the cropped frame about the center of the cropped frame.
        qDebug()<<"Rotate that image  "<<angle;
        bgracropped = rotateImage(bgracropped, angle);//Rotate full image about this center
        
        //after I rotate clear the global angle
        angle =0;
        //debug
        angle=-1;
        
        

        // Save the Nicely Rotated and Cropped Model File
        imwrite(modelfilename.toStdString(),bgracropped);
        
        
        centroids.clear();
        maxXY.clear();
        minXY.clear();
        paintCanvas->polyNames.clear();
        paintCanvas->polygons.clear();
        paintCanvas->masks.pop_back();
        polyinfo = "Polygon cleared";
        paintCanvas->temp.clear();
        ui->statusBar->showMessage(polyinfo,2000);
        paintCanvas->replyMask = replyNull;
        capture.set(CV_CAP_PROP_POS_FRAMES,(double)currentFrame);
    }
    
    
}
Beispiel #12
0
Mat Detector::detect(string imgname){
	//cout<<"Debug: "<<debug<<endl;
	Mat resized;
	IplImage *frame = cvLoadImage(imgname.data(), 2|4);
	if (frame == NULL)
    {
      fprintf(stderr, "Cannot open image %s.Returning empty Mat...\n", imgname.data());
      return resized;
    }
	
	else if (frame->width < 100 || frame->height < 100)
    {
      fprintf(stderr, "image %s too small.Returning empty Mat...\n", imgname.data());
      cvReleaseImage(&frame);
	  return resized;
    }	
	else if (frame->width > 100000 || frame->height > 100000)
    {
      fprintf(stderr, "image %s too large.Returning empty Mat...\n", imgname.data());
      cvReleaseImage(&frame);
	  return resized;
    }
	
	// convert image to grayscale
    IplImage *frame_bw = cvCreateImage(cvSize(frame->width, frame->height), IPL_DEPTH_8U, 1);
    cvConvertImage(frame, frame_bw);
	Mat frame_mat(frame, 1);
	// Smallest face size.
    CvSize minFeatureSize = cvSize(100, 100);
    int flags =  CV_HAAR_DO_CANNY_PRUNING;
    // How detailed should the search be.
    float search_scale_factor = 1.1f;
    CvMemStorage* storage;
    CvSeq* rects;
    int nFaces;
	
    storage = cvCreateMemStorage(0);
    cvClearMemStorage(storage);

    // Detect all the faces in the greyscale image.
   rects = cvHaarDetectObjects(frame_bw, faceCascade, storage, search_scale_factor, 2, flags, minFeatureSize);
    //rects = MBLBPDetectMultiScale(frame_bw, faceCascade, storage, 1229, 1, 50, 500);
	nFaces = rects->total;
	if (nFaces != 1){
		if (debug)
			printf("%d faces detected\n", nFaces);
		storage = cvCreateMemStorage(0);
		cvReleaseMemStorage(&storage);
		cvReleaseImage(&frame_bw);
		cvReleaseImage(&frame);	
		return resized;
	}
		
	int iface = 0;
	CvRect *r = (CvRect*)cvGetSeqElem(rects, iface);
	double* landmarks  = new double[2*fmodel->data.options.M];
	int bbox[4];
	bbox[0] = r->x;
	bbox[1] = r->y;
	bbox[2] = r->x + r->width;
	bbox[3] = r->y + r->height;
	
	// Detect landmarks
	flandmark_detect(frame_bw, bbox, fmodel, landmarks);
	
	//align faces
	double angle[3];
	angle[0] = atan((landmarks[7]-landmarks[9])/(landmarks[6]-landmarks[8]));
	angle[1] = atan((landmarks[11]-landmarks[13])/(landmarks[10]-landmarks[12]));
	angle[2] = atan((landmarks[3]-landmarks[5])/(landmarks[2]-landmarks[4]));
	//cout<<angle[0]*180<<" "<<angle[1]*180<<" "<<angle[2]*180<<endl;
	
	double angle_rotate = 0;
	if (angle[0] > angle[1]){
		if (angle[1] > angle[2])
			angle_rotate = angle[1];
		else if (angle[0] > angle[2])
			angle_rotate = angle[2];
		else
			angle_rotate = angle[0];
	}
	else{
		if (angle[1] < angle[2])
			angle_rotate = angle[1];
		else if (angle[2] < angle[0])
			angle_rotate = angle[0];
		else
			angle_rotate = angle[2];
	}
	Rect faceRect(r->x, r->y,r->width, r->height);

	//save face to tmp if debug
	if (debug){
		cvRectangle(frame, cvPoint(bbox[0], bbox[1]), cvPoint(bbox[2], bbox[3]), CV_RGB(255,0,0) );
		cvRectangle(frame, cvPoint(fmodel->bb[0], fmodel->bb[1]), cvPoint(fmodel->bb[2], fmodel->bb[3]), CV_RGB(0,0,255) );
		cvCircle(frame, cvPoint((int)landmarks[0], (int)landmarks[1]), 3, CV_RGB(0,0,255), CV_FILLED);
		cvCircle(frame, cvPoint(int(landmarks[2]), int(landmarks[3])), 3, CV_RGB(255,0,0), CV_FILLED);
		cvCircle(frame, cvPoint(int(landmarks[4]), int(landmarks[5])), 3, CV_RGB(255,0,0), CV_FILLED);
		cvCircle(frame, cvPoint(int(landmarks[6]), int(landmarks[7])), 3, CV_RGB(255,0,0), CV_FILLED);
		cvCircle(frame, cvPoint(int(landmarks[8]), int(landmarks[9])), 3, CV_RGB(255,0,0), CV_FILLED);
		cvCircle(frame, cvPoint(int(landmarks[10]), int(landmarks[11])), 3, CV_RGB(255,0,0), CV_FILLED);
		cvCircle(frame, cvPoint(int(landmarks[12]), int(landmarks[13])), 3, CV_RGB(255,0,0), CV_FILLED);
		cvCircle(frame, cvPoint(int(landmarks[14]), int(landmarks[15])), 3, CV_RGB(255,0,0), CV_FILLED);
		Mat face(frame, 0);
		Mat croppedFaceImage = face(faceRect).clone();
		Mat rotated = rotateImage(croppedFaceImage, angle_rotate * 180 / PI);
		resize(rotated, resized, Size(100, 100));
		imwrite( "./tmp/face.jpg" , resized );
	}
	delete [] landmarks;
	storage = cvCreateMemStorage(0);
	cvReleaseMemStorage(&storage);
	cvReleaseImage(&frame_bw);
	cvReleaseImage(&frame);
	
	if (faceRect.height < 50 && faceRect.width < 50){
		printf("Face too small: %d x %d\n", faceRect.height, faceRect.width);
		return resized;
	}
	Mat croppedFaceImage = frame_mat(faceRect).clone();
	Mat rotated = rotateImage(croppedFaceImage, angle_rotate * 180 / PI);
	resize(rotated, resized, Size(100, 100));
	return resized;
}
void ImageTransformation::writeImages(Mat imageBase, QString destinationPath, QString fileName, QString extension, MainWindow* mainW)
{

    Mat imageTemp;
    imageBase.copyTo(imageTemp);

    Mat imageRotate0 = imageTemp;
    Mat imageRotate90;
    Mat imageRotate180;
    Mat imageRotate270;

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

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

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

    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 + extension).toStdString(), imageRotate0 );
        imwrite((destinationPath + "/" + rotateImagesPath + fileName + "_R90" + extension).toStdString(), imageRotate90 );
        imwrite((destinationPath + "/" + rotateImagesPath + fileName + "_R180" + extension).toStdString(), imageRotate180 );
        imwrite((destinationPath + "/" + rotateImagesPath + fileName + "_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 + "_F0" + extension).toStdString(), imageFlipV0 );
            imwrite((destinationPath + "/" + rotateImagesPath + fileName + "_F90" + extension).toStdString(), imageFlipV90 );
            imwrite((destinationPath + "/" + rotateImagesPath + fileName + "_F180" + extension).toStdString(), imageFlipV180 );
            imwrite((destinationPath + "/" + rotateImagesPath + fileName + "_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 + "_F0" + extension).toStdString(), imageFlipV0 );

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

}
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 #15
0
void VideoCorrect::correctImage(Mat& inputFrame, Mat& outputFrame, bool developerMode){
	
	resize(inputFrame, inputFrame, CAMERA_RESOLUTION);
	inputFrame.copyTo(img);

	//Convert to YCbCr color space
	cvtColor(img, ycbcr, CV_BGR2YCrCb);

	//Skin color thresholding
	inRange(ycbcr, Scalar(0, 150 - Cr, 100 - Cb), Scalar(255, 150 + Cr, 100 + Cb), bw);

	if(IS_INITIAL_FRAME){
		face = detectFaces(img);
		if(face.x != 0){
			lastFace = face;
		}
		else{
			outputFrame = img;
			return;
		}
		prevSize = Size(face.width/2, face.height/2);
		head = Mat::zeros(bw.rows, bw.cols, bw.type());
		ellipse(head, Point(face.x + face.width/2, face.y + face.height/2), prevSize, 0, 0, 360, Scalar(255,255,255,0), -1, 8, 0);
		if(face.x > 0 && face.y > 0 && face.width > 0 && face.height > 0 
			&& (face.x + face.width) < img.cols && (face.y + face.height) < img.rows){
			img(face).copyTo(bestImg);
		}
		putText(img, "Give your best pose!", Point(face.x, face.y), CV_FONT_HERSHEY_SIMPLEX, 0.4, Scalar(255,255,255,0), 1, CV_AA);
	}

	firstFrameCounter--;

	if(face.x == 0) //missing face prevention
		face = lastFace;

	//Mask the background out
	bw &= head;

	//Compute more accurate image moments after background removal
	m = moments(bw, true);
	angle = (atan((2*m.nu11)/(m.nu20-m.nu02))/2)*180/PI;
	center = Point(m.m10/m.m00,m.m01/m.m00);

	//Smooth rotation (running average)
	bufferCounter++;
	rotationBuffer[ bufferCounter % SMOOTHER_SIZE ] = angle;
	smoothAngle += (angle - rotationBuffer[(bufferCounter + 1) % SMOOTHER_SIZE]) / SMOOTHER_SIZE;

	//Expand borders
	copyMakeBorder( img, img, BORDER_EXPAND, BORDER_EXPAND, BORDER_EXPAND, BORDER_EXPAND, 
					BORDER_REPLICATE, Scalar(255,255,255,0));

	if(!IS_INITIAL_FRAME){
		//Rotate the image to correct the leaning angle
		rotateImage(img, smoothAngle);
	
		//After rotation detect faces
		face = detectFaces(img);
		if(face.x != 0)
			lastFace = face;

		//Create background mask around the face
		head = Mat::zeros(bw.rows, bw.cols, bw.type());
		ellipse(head, Point(face.x - BORDER_EXPAND + face.width/2, face.y -BORDER_EXPAND + face.height/2),
					  prevSize, 0, 0, 360, Scalar(255,255,255,0), -1, 8, 0);

		//Draw a rectangle around the face
		//rectangle(img, face, Scalar(255,255,255,0), 1, 8, 0);

		//Overlay the ideal pose
		if(replaceFace && center.x > 0 && center.y > 0){
			center = Point(face.x + face.width/2, face.y + face.width/2);
			overlayImage(img, bestImg, center, smoothSize);
		}

	} else{
		face.x += BORDER_EXPAND; //position alignment after border expansion (not necessary if we detect the face after expansion)
		face.y += BORDER_EXPAND;
	}
	
	//Smooth ideal image size (running average)
	sizeBuffer[ bufferCounter % SMOOTHER_SIZE ] = face.width;
	smoothSize += (face.width - sizeBuffer[(bufferCounter + 1) % SMOOTHER_SIZE]) / SMOOTHER_SIZE;

	//Get ROI
	center = Point(face.x + face.width/2, face.y + face.width/2);
	roi = getROI(img, center);
	if(roi.x > 0 && roi.y > 0 && roi.width > 0 && roi.height > 0 
		&& (roi.x + roi.width) < img.cols && (roi.y + roi.height) < img.rows){
		img = img(roi);
	}

	//Resize the final image
	resize(img, img, CAMERA_RESOLUTION);

	if(developerMode){

		Mat developerScreen(img.rows, 
							img.cols + 
							inputFrame.cols +
							bw.cols, CV_8UC3);

		Mat left(developerScreen, Rect(0, 0, img.size().width, img.size().height));
		img.copyTo(left);

		Mat center(developerScreen, Rect(img.cols, 0, inputFrame.cols, inputFrame.rows));
		inputFrame.copyTo(center);

		cvtColor(bw, bw, CV_GRAY2BGR);
		Mat right(developerScreen, Rect(img.size().width + inputFrame.size().width, 0, bw.size().width, bw.size().height));
		bw.copyTo(right);

		Mat rightmost(developerScreen, Rect(img.size().width + inputFrame.size().width + bw.size().width - bestImg.size().width, 0,
											bestImg.size().width, bestImg.size().height));
		bestImg.copyTo(rightmost);

		outputFrame = developerScreen;
	}
	else{
		outputFrame = img;
	}
}
void SettingsButtonImage::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
{
	
	
	
	float halfAngle = endRadians - startRadians;
	halfAngle = halfAngle * 0.5;
	halfAngle = halfAngle + startRadians;
	
	float sinX = sin(halfAngle);
	float cosY = -cos(halfAngle);
	float midRadius = (getWidth() * 0.5) * (theWidth + ((1 - theWidth) * 0.5));
	//float xCo = (getWidth() * 0.5) + (midRadius * sinX);
	//float yCo =	(getHeight() * 0.5) + (midRadius * cosY);
											
	//float imageAngle = halfAngle - (startRadians + (M_PI / (4 *(M_PI / 180)))
	float maxImageWidth = ((getWidth() * 0.5) * (1 - theWidth)) * 0.7;
	float imageScale = (maxImageWidth * imageWidth) / theImage->getWidth();

	//float imageSinX = sin(imageAngle);
	//float imageCosY = -cos(imageAngle);
										
	float imageRadius = midRadius + ((maxImageWidth * 0.5) * imageWidth);
										
	float xImageCo = (getWidth() * 0.5) + (imageRadius * sinX);
											
	float yImageCo = (getHeight() * 0.5) + (imageRadius * cosY);
												
	
	AffineTransform rotateImage(AffineTransform::scale(imageScale, imageScale).
								AffineTransform::translated((xImageCo - ((maxImageWidth * 0.5) * imageWidth)), 
															yImageCo).
								AffineTransform::rotated(halfAngle, xImageCo, yImageCo));
	

	switch (getToggleState() ? (isButtonDown ? 5 : (isMouseOverButton ? 4 : 3))
			: (isButtonDown ? 2 : (isMouseOverButton ? 1 : 0)))
    {
		case 0:
        {
			ColourGradient fillGradient(AlphaTheme::getInstance()->backgroundColour, (getWidth() * 0.5), (getHeight() * 0.5), AlphaTheme::getInstance()->childBackgroundColour, 0, 0, true);
			g.setGradientFill(fillGradient);
			g.fillPath(thePath, getTransform());
			
			g.setColour(AlphaTheme::getInstance()->foregroundColourDarker.withAlpha(0.5f));
			g.strokePath (thePath, PathStrokeType(1.0f), getTransform());
			
			g.setColour(AlphaTheme::getInstance()->iconColour.withAlpha(0.5f));
			g.drawImageTransformed(*theImage, rotateImage, true);
			
            break;
        }
			
		case 1:
        {
			ColourGradient fillGradient(AlphaTheme::getInstance()->backgroundColour, (getWidth()*0.5), (getHeight()*0.5), AlphaTheme::getInstance()->childBackgroundColour, 0, 0, true);			
			g.setGradientFill(fillGradient);
			g.fillPath(thePath, getTransform());
			
			g.setColour(AlphaTheme::getInstance()->foregroundColourDarker.withAlpha(0.7f));
			g.strokePath (thePath, PathStrokeType(1.0f), getTransform());
			
			g.setColour(AlphaTheme::getInstance()->iconColour.withAlpha(0.8f));
			g.drawImageTransformed(*theImage, rotateImage, true);
			
            break;
        }
			
		case 2:
        {
			ColourGradient fillGradient(AlphaTheme::getInstance()->childBackgroundColour, (getWidth()*0.5), (getHeight()*0.5), AlphaTheme::getInstance()->backgroundColour, 0, 0, true);
			g.setGradientFill(fillGradient);
			g.fillPath(thePath, getTransform());
			
			g.setColour(AlphaTheme::getInstance()->foregroundColourDarker.withAlpha(0.7f));
			g.strokePath (thePath, PathStrokeType(1.0f), getTransform());
			
			g.setColour(AlphaTheme::getInstance()->iconColour.withAlpha(0.8f));
			g.drawImageTransformed(*theImage, rotateImage, true);
			
            break;
        }
			
		case 3:
        {
			ColourGradient fillGradient(AlphaTheme::getInstance()->childBackgroundColour, (getWidth()*0.5), (getHeight()*0.5), AlphaTheme::getInstance()->backgroundColour, 0, 0, true);
			g.setGradientFill(fillGradient);
			g.fillPath(thePath, getTransform());
			
			g.setColour(AlphaTheme::getInstance()->foregroundColourDarker.withAlpha(0.4f));
			g.strokePath (thePath, PathStrokeType(1.0f), getTransform());
			
			g.setColour(AlphaTheme::getInstance()->mainColour);
			g.drawImageTransformed(*theImage, rotateImage, true);
			
            break;
        }
			
		case 4:
        {
			ColourGradient fillGradient(AlphaTheme::getInstance()->childBackgroundColour, (getWidth()*0.5), (getHeight()*0.5), AlphaTheme::getInstance()->backgroundColour, 0, 0, true);
			g.setGradientFill(fillGradient);
			g.fillPath(thePath, getTransform());
			
			g.setColour(AlphaTheme::getInstance()->foregroundColourDarker.withAlpha(0.4f));
			g.strokePath (thePath, PathStrokeType(1.0f), getTransform());
			
			g.setColour(AlphaTheme::getInstance()->mainColour);
			
			g.drawImageTransformed(*theImage, rotateImage, true);
			
            break;
        }
			
		case 5:
        {
			ColourGradient fillGradient(AlphaTheme::getInstance()->childBackgroundColour, (getWidth()*0.5), (getHeight()*0.5), AlphaTheme::getInstance()->backgroundColour, 0, 0, true);
			g.setGradientFill(fillGradient);
			g.fillPath(thePath, getTransform());
			
			g.setColour(AlphaTheme::getInstance()->foregroundColourDarker.withAlpha(0.4f));
			g.strokePath (thePath, PathStrokeType(1.0f), getTransform());
			
			g.setColour(AlphaTheme::getInstance()->mainColour);
			
			g.drawImageTransformed(*theImage, rotateImage, true);
			
            break;
        }
			
		default:
			break;
    }
}
Beispiel #17
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;
}
Beispiel #18
0
// Loads the next image in the set, deletes the "last image" and
// moves the currently decoded one to last image.
int ISSImages::loadNextImage()
{
	if ( filenames.size() <= 0 )
	{
		printf("ERROR, no files to load\n");
		return -1;
	}

	// Iterate our image safely
	if ( current_image + 1 == filenames.end() )
		current_image = filenames.begin();
	else
		current_image++;

	// Rotate decoded images
	if ( previous_image_surface )
		SDL_FreeSurface(previous_image_surface);
	if ( current_image_surface )
		previous_image_surface = current_image_surface;

	// Begin our load
	std::cout << "Loading image " << *current_image << "...";

	FILE *fp = fopen((*current_image).c_str(), "rb");
	if ( !fp )
	{
		printf("Can't open file.\n");
		return -1;
	}

	// Determine the size of the file for our buffer
	fseek(fp, 0, SEEK_END);
	unsigned long fsize = ftell(fp);
	rewind(fp);

	// Make a memory buffer the size of the image on our heap
	unsigned char *buf = new unsigned char[fsize];

	// Read the file into our buffer
	if ( fread(buf, 1, fsize, fp) != fsize)
	{
		printf("Can't read file.\n");
		return -1;
	}
	fclose(fp);

	// Parse the exif data to get the rotation
	EXIFInfo result;
	ParseEXIF(buf, fsize, result);

	// Create an SDL_RWops since we already have the file loaded, we don't
	// need another buffer with it, we'll load it and create a surface
	// from the buffer already containing the JPEG
	SDL_RWops *file;
	file = SDL_RWFromMem( buf, fsize );
	current_image_surface = IMG_Load_RW( file, 0 );
	SDL_FreeRW(file);

	if ( ! current_image_surface )
	{
		printf("ERROR Loading image!\n");
		return -1;
	}
	delete[] buf;
	printf("done\n");


	// rotate the image if necessary
	// we want to do this before scaling because it will change whether it's
	// scaled to the W or the H to fit our display
	// -----------------------------------------------------------------------------
	int rotation = 0;
	bool mirrored = false;
	switch (result.orientation)
	{
		case 7:
			mirrored = true;
		case 8:
			rotation = 270;
			break;

		case 5:
			mirrored = true;
		case 6:
			rotation = 90;
			break;

		case 4:
			mirrored = true;
		case 3:
			rotation = 180;
			break;

		case 2:
			mirrored = true;
		case 1:
			rotation = 0;
			break;
	}

	if ( mirrored || rotation )
	{
		printf("Rotating image...");
		if ( rotateImage(rotation, mirrored) )
			printf("ERROR Rotating image!\n");
		else
			printf("done\n");
	}

	// scale the image if necessary
	// -----------------------------------------------------------------------------

	int w = current_image_surface->w;
	int h = current_image_surface->h;

	if (w != 800)
	{
		h = (h * 800) / w;
		w = 800;
	}

	if (h > 600)
	{
		w = (w * 600) / h;
		h = 600;
	}

	if ( w != current_image_surface->w || h != current_image_surface->h)
	{
		printf("Scaling image...");
		if ( scaleImage(w, h) )
			printf("ERROR Scaling image!\n");
		else
			printf("done\n");
	}

	// frame the scaled image, if necessary
	// -----------------------------------------------------------------------------

	if ( 800 != current_image_surface->w || 600 != current_image_surface->h)
	{
		printf("Framing image...");
		if ( frameImage(800, 600) )
			printf("ERROR Framing image!\n");
		else
			printf("done\n");
	}

	// return success
	// -----------------------------------------------------------------------------
	return 0;
}
IplImage* getStroke(const char *filename)
{
	// 加载原图    
	IplImage *pStrokeImage = cvLoadImage(filename, CV_LOAD_IMAGE_GRAYSCALE);
	Image gray(pStrokeImage);
	//Sobel算子 边缘检测
	for (int i = 0; i < gray.getH() - 2; i++)
		for (int j = 0; j < gray.getW() - 2; j++)
		{
			int cx = (2 * gray[i + 2][j + 1] + gray[i + 2][j] + gray[i + 2][j + 2])
				- (2 * gray[i][j + 1] + gray[i][j] + gray[i][j + 2]);
			int cy = (2 * gray[i + 1][j + 2] + gray[i][j + 2] + gray[i + 2][j + 2])
				- (2 * gray[i + 1][j] + gray[i][j] + gray[i + 2][j]);

			/*梯度算子 边缘检测
			cx = gray[i+1][j] - gray[i][j];
			cy = gray[i][j+1] - gray[i][j];
			*/
			gray[i][j] = sqrt(cx*cx + cy*cy);
		}
	Mat sobel;
	Mat(pStrokeImage).convertTo(sobel, CV_32FC1);
	sobel /= 256;

	//选取dirNum个方向检测
	int dirNum = 8;
	//计算L0
	int sz = 5;
	int len = sz * 2 + 1;
	Mat L(len, len, CV_32FC1, Scalar::all(0));
	for (int i = 0; i < len; i++) L.at<float>(sz, i) = 1.0/len;

	//计算Li与Gi
	Mat *l = new Mat[dirNum];
	Mat *G = new Mat[dirNum];
	for (int i = 0; i < dirNum; i++)
	{
		l[i] = rotateImage(L, i * 180.0 / dirNum);
		conv2(sobel, l[i], G[i]);
	}

	//初始化并计算Ci
	Mat *C = new Mat[dirNum];
	for (int i = 0; i < dirNum; i++)
		C[i] = Mat(gray.getH(), gray.getW(), CV_32FC1, Scalar::all(0));

	for (int i = 0; i < gray.getH(); i++)
		for (int j = 0; j < gray.getW(); j++) {
			int key = 0;
			for (int k = 1; k < dirNum; k++)
				if (G[key].at<float>(i, j) < G[k].at<float>(i, j))
					key = k;
			C[key].at<float>(i, j) = sobel.at<float>(i, j);
		}

	//计算S
	Mat temp;
	Mat S(gray.getH(), gray.getW(), CV_32FC1, Scalar::all(0));
	for (int i = 0; i < dirNum; i++) {
		conv2(C[i], l[i], temp);
		S += temp;
	}
	float Max = 0;
	for (int i = 0; i < S.rows; i++)
		for (int j = 0; j < S.cols; j++) Max = max(Max, S.at<float>(i, j));
	S = (1 - S / Max) * 240;

	for (int i = 0; i < S.rows; i++)
		for (int j = 0; j < S.cols; j++) gray[i][j] = S.at<float>(i, j);
	return pStrokeImage;
}
Beispiel #20
0
RImage*
RRotateImage(RImage *image, float angle)
{
    RImage *img;
    int nwidth, nheight;
    int x, y;
    int bpp = image->format == RRGBAFormat ? 4 : 3;

    angle = ((int)angle % 360) + (angle - (int)angle);

    if (angle == 0.0) {
        return RCloneImage(image);

    } else if (angle == 90.0) {
        nwidth = image->height;
        nheight = image->width;

        img = RCreateImage(nwidth, nheight, True);
        if (!img) {
            return NULL;
        }

        if (bpp == 3) {
            unsigned char *optr, *nptr;
            unsigned offs;


            offs = nwidth * 4;

            optr = image->data;
            nptr = img->data;

            for (x = 0; x < nwidth; x++) {
                nptr = img->data + x*4;
                for (y = nheight; y; y--) {
                    nptr[0] = *optr++;
                    nptr[1] = *optr++;
                    nptr[2] = *optr++;
                    nptr[3] = 255;

                    nptr += offs;
                }
            }
        } else {
            unsigned *optr, *nptr;
            unsigned *p;

            optr = (unsigned*)image->data;
            p = (unsigned*)img->data;
            for (x = 0; x < nwidth; x++) {
                nptr = p++;
                for (y = nheight; y; y--) {
                    *nptr = *optr++;
                    nptr += nwidth;
                }
            }
        }
    } else if (angle == 180.0) {

        nwidth = image->width;
        nheight = image->height;
        img = RCreateImage(nwidth, nheight, True);
        if (!img) {
            return NULL;
        }

        if (bpp == 3) {
            unsigned char *optr, *nptr;

            optr = image->data;
            nptr = img->data + nwidth * nheight * 4 - 4;

            for (y = 0; y < nheight; y++) {
                for (x = 0; x < nwidth; x++) {
                    nptr[0] = optr[0];
                    nptr[1] = optr[1];
                    nptr[2] = optr[2];
                    nptr[3] = 255;

                    optr += 3;
                    nptr -= 4;
                }
            }
        } else {
            unsigned *optr, *nptr;

            optr = (unsigned*)image->data;
            nptr = (unsigned*)img->data + nwidth * nheight - 1;

            for (y = nheight*nwidth-1; y >= 0; y--) {
                *nptr = *optr;
                optr++;
                nptr--;
            }
        }
    } else if (angle == 270.0) {
        nwidth = image->height;
        nheight = image->width;

        img = RCreateImage(nwidth, nheight, True);
        if (!img) {
            return NULL;
        }

        if (bpp == 3) {
            unsigned char *optr, *nptr;
            unsigned offs;


            offs = nwidth * 4;

            optr = image->data;
            nptr = img->data;

            for (x = 0; x < nwidth; x++) {
                nptr = img->data + x*4;
                for (y = nheight; y; y--) {
                    nptr[0] = *optr++;
                    nptr[1] = *optr++;
                    nptr[2] = *optr++;
                    nptr[3] = 255;

                    nptr += offs;
                }
            }
        } else {
            unsigned *optr, *nptr;
            unsigned *p;

            optr = (unsigned*)image->data;
            p = (unsigned*)img->data + nwidth*nheight;
            for (x = 0; x < nwidth; x++) {
                nptr = p--;
                for (y = nheight; y; y--) {
                    *nptr = *optr++;
                    nptr -= nwidth;
                }
            }
        }
    } else {
        img = rotateImage(image, angle);
    }

    return img;
}
Beispiel #21
0
void Scene::rotateCW() {
  emit rotateImage(1);
}