001package org.openimaj.demos.sandbox.tldcpp.tracker; 002 003import java.awt.event.MouseEvent; 004import java.awt.event.MouseListener; 005import java.awt.event.MouseMotionListener; 006 007import org.openimaj.demos.sandbox.tldcpp.videotld.TLDMain; 008import org.openimaj.image.MBFImage; 009import org.openimaj.image.colour.RGBColour; 010import org.openimaj.math.geometry.point.Point2dImpl; 011import org.openimaj.math.geometry.shape.Rectangle; 012 013public class RectangleSelectionListener implements MouseListener, MouseMotionListener { 014 015 private TLDMain tldMain; 016 private boolean rectangleSelectMode; 017 private Point2dImpl start; 018 private Point2dImpl end; 019 private Rectangle currentRect; 020 021 public RectangleSelectionListener(TLDMain tldMain) { 022 this.tldMain = tldMain; 023 this.rectangleSelectMode = false; 024 } 025 026 @Override 027 public void mouseClicked(MouseEvent e) { 028 mousePressed(e); 029 } 030 031 @Override 032 public void mousePressed(MouseEvent e) { 033 if(rectangleSelectMode){ 034 this.start = new Point2dImpl(e.getX(),e.getY()); 035 } 036 } 037 038 @Override 039 public void mouseReleased(MouseEvent e) { 040 if(rectangleSelectMode){ 041 this.end = new Point2dImpl(e.getX(),e.getY()); 042 try { 043 tldMain.selectObject(getRect(start,end)); 044 } catch (Exception e1) { 045 e1.printStackTrace(); 046 } 047 this.rectangleSelectMode = false; 048 this.currentRect = null; 049 } 050 } 051 052 private Rectangle getRect(Point2dImpl start, Point2dImpl end) { 053 float x = Math.min(start.x, end.x); 054 float y = Math.min(start.y, end.y); 055 float width = Math.abs(start.x - end.x); 056 float height = Math.abs(start.y - end.y); 057 return new Rectangle(x,y,width,height); 058 } 059 060 @Override 061 public void mouseEntered(MouseEvent e) {} 062 063 @Override 064 public void mouseExited(MouseEvent e) {} 065 066 public void selectBoundingBox() { 067 this.currentRect = new Rectangle(0,0,1,1); 068 this.rectangleSelectMode = true; 069 } 070 071 public Rectangle currentRect(){ 072 if(!this.rectangleSelectMode) return null; 073 return this.currentRect; 074 } 075 076 @Override 077 public void mouseDragged(MouseEvent e) { 078 if(this.rectangleSelectMode){ 079 end = new Point2dImpl(e.getX(),e.getY()); 080 this.currentRect = getRect(start,end); 081 } 082 } 083 084 @Override 085 public void mouseMoved(MouseEvent e) { 086 // TODO Auto-generated method stub 087 088 } 089 090 public boolean drawRect(MBFImage frame) { 091 if(this.rectangleSelectMode){ 092 frame.drawShape(this.currentRect, RGBColour.RED); 093 return true; 094 } 095 else{ 096 return false; 097 } 098 } 099 100}