Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Drawing with Mouse on Images using Python-OpenCV
Next article icon
OpenCV is an open-source computer vision and machine learning software library. Various image processing operations such as manipulating images and applying tons of filters can be done with the help of it. It is broadly used in Object detection, Face Detection, and other Image processing tasks. Let's see how to draw rectangular shape on image and extract the objects using OpenCV.Python3
# Python program to extract rectangular# Shape using OpenCV in Python3importcv2importnumpyasnpdrawing=False# true if mouse is pressedmode=True# if True, draw rectangle.ix,iy=-1,-1# mouse callback functiondefdraw_circle(event,x,y,flags,param):globalix,iy,drawing,modeifevent==cv2.EVENT_LBUTTONDOWN:drawing=Trueix,iy=x,yelifevent==cv2.EVENT_MOUSEMOVE:ifdrawing==True:ifmode==True:cv2.rectangle(img,(ix,iy),(x,y),(0,255,0),3)a=xb=yifa!=x|b!=y:cv2.rectangle(img,(ix,iy),(x,y),(0,0,0),-1)else:cv2.circle(img,(x,y),5,(0,0,255),-1)elifevent==cv2.EVENT_LBUTTONUP:drawing=Falseifmode==True:cv2.rectangle(img,(ix,iy),(x,y),(0,255,0),2)else:cv2.circle(img,(x,y),5,(0,0,255),-1)img=np.zeros((512,512,3),np.uint8)cv2.namedWindow('image')cv2.setMouseCallback('image',draw_circle)while(1):cv2.imshow('image',img)k=cv2.waitKey(1)&0xFFifk==ord('m'):mode=notmodeelifk==27:breakcv2.destroyAllWindows()
Output:
Above piece of code will work with only black background image. But rectangles can be drawn to any images. We can write a program which allows us to select desired portion in an image and extract that selected portion as well. The task includes following things -
  • draw shape on any image
  • re-select the extract portion for in case bad selection
  • extract particular object from the image
Python3
# Write Python code here# import the necessary packagesimportcv2importargparse# now let's initialize the list of reference pointref_point=[]crop=Falsedefshape_selection(event,x,y,flags,param):# grab references to the global variablesglobalref_point,crop# if the left mouse button was clicked, record the starting# (x, y) coordinates and indicate that cropping is being performedifevent==cv2.EVENT_LBUTTONDOWN:ref_point=[(x,y)]# check to see if the left mouse button was releasedelifevent==cv2.EVENT_LBUTTONUP:# record the ending (x, y) coordinates and indicate that# the cropping operation is finishedref_point.append((x,y))# draw a rectangle around the region of interestcv2.rectangle(image,ref_point[0],ref_point[1],(0,255,0),2)cv2.imshow("image",image)# construct the argument parser and parse the argumentsap=argparse.ArgumentParser()ap.add_argument("-i","--image",required=True,help="Path to the image")args=vars(ap.parse_args())# load the image, clone it, and setup the mouse callback functionimage=cv2.imread(args["image"])clone=image.copy()cv2.namedWindow("image")cv2.setMouseCallback("image",shape_selection)# keep looping until the 'q' key is pressedwhileTrue:# display the image and wait for a keypresscv2.imshow("image",image)key=cv2.waitKey(1)&0xFF# press 'r' to reset the windowifkey==ord("r"):image=clone.copy()# if the 'c' key is pressed, break from the loopelifkey==ord("c"):breakiflen(ref_point)==2:crop_img=clone[ref_point[0][1]:ref_point[1][1],ref_point[0][0]:ref_point[1][0]]cv2.imshow("crop_img",crop_img)cv2.waitKey(0)# close all open windowscv2.destroyAllWindows()
Run : Save the file ascapture_events.py and for testing select a demo picture which is located in the same directory. Now, execute the following command -
python capture_events.py --image demo.jpg
Output: First select the desired portion from the image. In addition, we can remove bad selection by pressing ‘r’ as programmed for making a new proper selection.
Fig: Selected Portion
Now after selecting a proper selection like above, just press ‘c’ to extract, as programmed.Fig: Cut Portion

Improve
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp