|
| 1 | +''' |
| 2 | +Referred to example 4-1 in the book "Learning OpenCV: Computer Vision with the OpenCV Library" |
| 3 | +
|
| 4 | +Example 4-1. Toy program for using a mouse to draw boxes on the screen |
| 5 | +
|
| 6 | +Converted to Python by Abid.K --mail me at [email protected] |
| 7 | +''' |
| 8 | +######################################################################################## |
| 9 | + |
| 10 | +import cv |
| 11 | +# cvRect box=[box.x,box.y,box.width,box.height] |
| 12 | +box=[0,0,0,0] |
| 13 | + |
| 14 | +# creating mouse callback function |
| 15 | +def my_mouse_callback(event,x,y,flags,param): |
| 16 | + global drawing_box |
| 17 | + if event==cv.CV_EVENT_LBUTTONDOWN: |
| 18 | + drawing_box=True |
| 19 | + [box[0],box[1],box[2],box[3]]=[x,y,0,0] |
| 20 | + print box[0] |
| 21 | + |
| 22 | + if event==cv.CV_EVENT_LBUTTONUP: |
| 23 | + drawing_box=False |
| 24 | + if box[2]<0: |
| 25 | + box[0]+=box[2] |
| 26 | + box[2]*=-1 |
| 27 | + if box[3]<0: |
| 28 | + box[1]+=box[3] |
| 29 | + box[3]*=-1 |
| 30 | + |
| 31 | + if event==cv.CV_EVENT_MOUSEMOVE: |
| 32 | + if (drawing_box==True): |
| 33 | + box[2]=x-box[0] |
| 34 | + box[3]=y-box[1] |
| 35 | + |
| 36 | +# function to draw the rectangle, added flag -1 to fill rectangle. If you don't want to fill, just delete it. |
| 37 | +def draw_box(img,box): |
| 38 | + cv.Rectangle(img,(box[0],box[1]),(box[0]+box[2],box[1]+box[3]),(255,0,0),-1) |
| 39 | + |
| 40 | +# main program |
| 41 | +drawing_box=False |
| 42 | +image=cv.CreateImage((200,200),cv.IPL_DEPTH_8U,3) |
| 43 | +# make a clone of image |
| 44 | +temp=cv.CloneImage(image) |
| 45 | + |
| 46 | +cv.NamedWindow("Box Example") |
| 47 | +cv.SetMouseCallback("Box Example",my_mouse_callback,image) |
| 48 | +while(1): |
| 49 | + cv.Copy(image,temp) |
| 50 | + if drawing_box==True: |
| 51 | + draw_box(temp,box) |
| 52 | + cv.ShowImage("Box Example",temp) |
| 53 | + if cv.WaitKey(20)%0x100==27:break |
| 54 | + |
| 55 | +cv.DestroyWindow("Box Example") |
| 56 | +################################################################################################### |
0 commit comments