QNA > H > How To Detect An Object From Static Image And Crop It From The Image Using Opencv

How to detect an object from static image and crop it from the image using openCV

Use opencv. Find the contours in the image, and then crop it. Here is the sample code.

To find the contours:

  1. import cv2 
  2. #reading the image  
  3. image = cv2.imread("example.jpg") 
  4. edged = cv2.Canny(image, 10, 250) 
  5. cv2.imshow("Edges", edged) 
  6. cv2.waitKey(0) 
  7.  
  8. #applying closing function  
  9. kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (7, 7)) 
  10. closed = cv2.morphologyEx(edged, cv2.MORPH_CLOSE, kernel) 
  11. cv2.imshow("Closed", closed) 
  12. cv2.waitKey(0) 
  13.  
  14. #finding_contours  
  15. (cnts, _) = cv2.findContours(closed.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) 
  16.  
  17. for c in cnts: 
  18. peri = cv2.arcLength(c, True) 
  19. approx = cv2.approxPolyDP(c, 0.02 * peri, True) 
  20. cv2.drawContours(image, [approx], -1, (0, 255, 0), 2) 
  21. cv2.imshow("Output", image) 
  22. cv2.waitKey(0) 

The image I have used for this is,

main-qimg-79e2b2e7bdd3e20ade7b91447e1a8bf9.webp

The output is,

main-qimg-7e000e373c4417a19fae5ff1d34e4766.webp

I’m just a beginner and will upload how to crop the image using contours once I learn.

UPDATE: Adding crop image part.

  1. import cv2  
  2. image = cv2.imread("example.jpg") 
  3. gray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) 
  4. edged = cv2.Canny(image, 10, 250) 
  5. (cnts, _) = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) 
  6. idx = 0 
  7. for c in cnts: 
  8. x,y,w,h = cv2.boundingRect(c) 
  9. if w>50 and h>50: 
  10. idx+=1 
  11. new_img=image[y:y+h,x:x+w] 
  12. cv2.imwrite(str(idx) + '.png', new_img) 
  13. cv2.imshow("im",image) 
  14. cv2.waitKey(0) 
main-qimg-03086a7435d39d54a0e88defb0fa7883.webp

This is the output which I got after running the code. It’s accuracy is almost 100% except the 3rd image.

Di Herzen

Cosa succede a un'auto (in garage) se non viene guidata per un anno? :: Perché gli screenshot sono salvati in formato .PNG?
Link utili