Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import cv2
- import numpy as np
- # import image
- image = cv2.imread('Snickers_0.bmp')
- cv2.imshow('original', image)
- # creating kernel
- kernel = np.ones((20, 20), np.uint8)
- # convert image into grayscale
- grayscale_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
- cv2.imshow('gray', grayscale_image)
- # binary image
- ret, thresh = cv2.threshold(grayscale_image, 70, 255, cv2.THRESH_BINARY)
- cv2.imshow('threshold', thresh)
- # performing morphological transformation - closing
- closing = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
- cv2.imshow('morphological closing', closing)
- ctrs, hier = cv2.findContours(closing.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
- # sort contours
- sorted_ctrs = sorted(ctrs, key=lambda ctr: cv2.boundingRect(ctr)[0])
- for i, ctr in enumerate(sorted_ctrs):
- # Get bounding box
- x, y, w, h = cv2.boundingRect(ctr)
- x -= 10
- y -= 10
- w += 10
- h += 10
- if w <= 30 or h <= 30:
- continue
- print("x min: {}", x)
- print("y min: {}", y)
- print("x max: {}", x+w)
- print("y max: {}", y+h)
- # Getting ROI
- roi = image[y:y + h, x:x + w]
- cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
- cv2.imshow('marked areas', image)
- cv2.waitKey(0)
- '''
- # binary
- ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)
- cv2.imshow('threshold', thresh)
- thresh = cv2.bitwise_not(thresh)
- cv2.imshow('inverted threshold', thresh)
- ctrs, hier = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
- # sort contours
- sorted_ctrs = sorted(ctrs, key=lambda ctr: cv2.boundingRect(ctr)[0])
- for i, ctr in enumerate(sorted_ctrs):
- # Get bounding box
- x, y, w, h = cv2.boundingRect(ctr)
- # Getting ROI
- roi = image[y:y + h, x:x + w]
- # show ROI
- # cv2.imshow('segment no:'+str(i),roi)
- cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
- if w > 15 and h > 15:
- cv2.imwrite('C:\\Users\\PC\\Desktop\\output\\{}.png'.format(i), roi)
- cv2.imshow('marked areas', image)
- cv2.waitKey(0)
- '''
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement