SHARE
TWEET

Untitled

a guest Oct 21st, 2019 65 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import cv2
  2. import numpy as np
  3.  
  4. # import image
  5. image = cv2.imread('Snickers_0.bmp')
  6. cv2.imshow('original', image)
  7.  
  8. # creating kernel
  9. kernel = np.ones((20, 20), np.uint8)
  10.  
  11. # convert image into grayscale
  12. grayscale_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  13. cv2.imshow('gray', grayscale_image)
  14.  
  15. # binary image
  16. ret, thresh = cv2.threshold(grayscale_image, 70, 255, cv2.THRESH_BINARY)
  17. cv2.imshow('threshold', thresh)
  18.  
  19. # performing morphological transformation - closing
  20.  
  21. closing = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
  22. cv2.imshow('morphological closing', closing)
  23.  
  24. ctrs, hier = cv2.findContours(closing.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  25.  
  26. # sort contours
  27. sorted_ctrs = sorted(ctrs, key=lambda ctr: cv2.boundingRect(ctr)[0])
  28.  
  29. for i, ctr in enumerate(sorted_ctrs):
  30.     # Get bounding box
  31.     x, y, w, h = cv2.boundingRect(ctr)
  32.     x -= 10
  33.     y -= 10
  34.     w += 10
  35.     h += 10
  36.  
  37.     if w <= 30 or h <= 30:
  38.         continue
  39.  
  40.     print("x min: {}", x)
  41.     print("y min: {}", y)
  42.     print("x max: {}", x+w)
  43.     print("y max: {}", y+h)
  44.  
  45.     # Getting ROI
  46.     roi = image[y:y + h, x:x + w]
  47.  
  48.     cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
  49.  
  50.  
  51. cv2.imshow('marked areas', image)
  52. cv2.waitKey(0)
  53. '''
  54. # binary
  55. ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)
  56. cv2.imshow('threshold', thresh)
  57.  
  58. thresh = cv2.bitwise_not(thresh)
  59.  
  60. cv2.imshow('inverted threshold', thresh)
  61.  
  62. ctrs, hier = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  63.  
  64. # sort contours
  65. sorted_ctrs = sorted(ctrs, key=lambda ctr: cv2.boundingRect(ctr)[0])
  66.  
  67. for i, ctr in enumerate(sorted_ctrs):
  68.     # Get bounding box
  69.     x, y, w, h = cv2.boundingRect(ctr)
  70.  
  71.     # Getting ROI
  72.     roi = image[y:y + h, x:x + w]
  73.  
  74.     # show ROI
  75.     # cv2.imshow('segment no:'+str(i),roi)
  76.     cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
  77.  
  78.     if w > 15 and h > 15:
  79.         cv2.imwrite('C:\\Users\\PC\\Desktop\\output\\{}.png'.format(i), roi)
  80.  
  81. cv2.imshow('marked areas', image)
  82. cv2.waitKey(0)
  83. '''
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top