import numpy as np import cv2 import matplotlib.pyplot as plt img = cv2.imread('./images/pill_002.png') gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) ret,thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) plt.subplot(221),plt.imshow(thresh,cmap='gray'),plt.title('thresh') # noise removal kernel = np.ones((3,3),np.uint8) opening = cv2.morphologyEx(thresh,cv2.MORPH_OPEN,kernel,iterations=2) sure_bg = cv2.dilate(opening,kernel,iterations=1) plt.subplot(222),plt.imshow(sure_bg,cmap='gray'),plt.title('sure_bg') plt.show()