1 # Author:Winter Liu is coming!
2 import cv2 as cv
3 import numpy as np
4 import matplotlib.pyplot as plt
5
6
7 src = cv.imread(r"C:\PycharmProjects\OpenCV\pic\rice.png")
8 cv.imshow("original", src)
9 gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
10 gray = cv.GaussianBlur(gray, (3, 3), 0)
11 ret, thresh = cv.threshold(gray, 50, 255, cv.THRESH_BINARY)
12 contours, hierarchy = cv.findContours(thresh, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
13 copy_img = src.copy()
14 cv.drawContours(copy_img, contours, -1, (255, 0, 0), 2)
15 cv.imshow("contours", copy_img)
16 print(len(contours))
17
18 cv.waitKey(0)
19 cv.destroyAllWindows()