import opencv.cv as cv
import opencv.highgui as hg
import sys
roi_x0 = 0
roi_y0 = 0
roi_x1 = 0
roi_y1 = 0
startDraw = 0
image = cv.IplImage
window_name = "Press c to capture"
draw = "Mark"
crop = "ROI"
result = "Result"
def on_mouse(event,x,y,flag,param):
global startDraw,im,roi_x0,roi_x1,roi_y0,roi_y1
if(event == hg.CV_EVENT_LBUTTONDOWN):
if(startDraw == 0):
roi_x0 = x
roi_y0 = y
startDraw = 1
else:
roi_x1 = x
roi_y1 = y
startDraw = 0
if(event==hg.CV_EVENT_MOUSEMOVE and startDraw == 1):
image2 = cv.cvCloneImage(image)
cv.cvRectangle(image2,cv.cvPoint(roi_x0,roi_y0),cv.cvPoint(x,y),cv.CV_RGB(255,0,255),1)
hg.cvShowImage(draw,image2)
def main():
global image
capture = hg.cvCreateCameraCapture(0)
hg.cvNamedWindow(window_name,1)
hg.cvSetMouseCallback(window_name,on_mouse,None)
flag = 1
while flag == 1:
image = hg.cvQueryFrame(capture)
key = hg.cvWaitKey(2)
im = image
if key == 'e':
sys.exit()
if key == 'a':
if roi_x0<roi_x1 and roi_y0<roi_y1:
r = cv.cvRect(roi_x0,roi_y0,roi_x1-roi_x0,roi_y1-roi_y0)
cropped = cv.cvCreateImage( cv.cvSize(roi_x1-roi_x0, roi_y1-roi_y0), 8, 3)
src_region = cv.cvGetSubRect(image,r)
cv.cvCopy(src_region, cropped)
#cv.cvReleaseImage(image)
if roi_x1<roi_x0 and roi_y1<roi_y0:
r = cv.cvRect(roi_x0,roi_y0,roi_x0-roi_x1,roi_y0-roi_y1)
cropped = cv.cvCreateImage( cv.cvSize(roi_x0-roi_x1, roi_y0-roi_y1), 8, 3)
src_region = cv.cvGetSubRect(image, r)
cv.cvCopy(src_region, cropped)
#cv.cvReleaseImage(image)
hg.cvSaveImage("1.jpg",src_region)
res_width = 640 - src_region.width + 1
res_height = 480 - src_region.height + 1
res = cv.cvCreateImage(cv.cvSize(res_width,res_height),cv.IPL_DEPTH_32F,1)
hg.cvDestroyAllWindows()
flag = 0
else:
hg.cvShowImage(window_name, image)
while True:
image = hg.cvQueryFrame(capture)
hg.cvShowImage(result,image)
key = hg.cvWaitKey(2)
if key == 'e':
sys.exit()
elif key == 'c':
hg.cvSaveImage("Image1.jpg",image)
im = hg.cvLoadImage("Image1.jpg")
cv.cvMatchTemplate(image,src_region,res, cv.CV_TM_SQDIFF )
minval, maxval, minloc, maxloc = cv.cvMinMaxLoc( res, 0 );
cv.cvRectangle( im, cv.cvPoint(minloc.x, minloc.y),cv.cvPoint( minloc.x + src_region.width, minloc.y + src_region.height ),cv.cvScalar( 0, 0, 255, 0 ), 1, 0, 0 );
hg.cvSaveImage("ggg.jpg",im)
hg.cvWaitKey(2)
hg.cvDestroyWindow(result)
cv.cvReleaseImage(image)
if __name__ == "__main__":
main()