使用opencv识别种子,并标出种子的数量

在进行学习opencv时老师给留了一个学习的任务,识别出种子,并且算出种子的个数,并显示出来。下面是原图

使用opencv识别种子,并标出种子的数量_第1张图片

 我对它进行代码的实现是

import cv2

import numpy as np

font=cv2.FONT_HERSHEY_COMPLEX

# Read image

img = cv2.imread('image/red.jpg')

# cv2.namedWindow('img',cv2.WINDOW_NORMAL)

# cv2.resizeWindow('img',2080,1080)

b = img[:, :, 0].copy()

g = img[:, :, 1].copy()

r = img[:, :, 2].copy()

out=r-0.81*b

out = out.astype(np.uint8)

# 阈值二值化

thresh,dst=cv2.threshold(out,60,255,cv2.THRESH_BINARY)

dst=~dst

kernel=cv2.getStructuringElement(cv2.MORPH_RECT,(9,9))

#先腐蚀

dst1=cv2.erode(dst,kernel,iterations=1)

#膨胀

dst2=cv2.dilate(dst1,kernel,iterations=1)

# 查找轮廓,返回轮廓和层级

result,contours,hierarchy=cv2.findContours(dst2,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

#对原图进行绘制边界处理

cv2.drawContours(img,contours,-1,(0,0,0),2)

for cnt in contours:

    (x,y),radius = cv2.minEnclosingCircle(cnt)

    center = (int(x),int(y))

    radius = int(radius)

    circle_img = cv2.circle(dst2, center, radius, (255, 255, 255), 1)

    area = cv2.contourArea(cnt)

    print(area)

    area=int(area)

    if area<1685:

        img = cv2.putText(img, '1', center, font, 0.5, (0, 255, 255))

    elif area>=1685 and area<2900:

        img = cv2.putText(img, '2', center, font, 0.5, (0, 255, 0))

    elif area >= 2900 and area < 4700:

        img = cv2.putText(img, '3', center, font, 0.5, (255, 0, 200))

    elif area >= 4700 and area < 5500:

        img = cv2.putText(img, '4', center, font, 0.5, (255, 200, 200))

    elif area >= 5500 and area < 7500:

        img = cv2.putText(img, '5', center, font, 0.5, (100, 100, 200))

    else:

        img = cv2.putText(img, '6', center, font, 0.5, (255, 255, 255))

cv2.imshow("img", img)

cv2.waitKey(0)

cv2.destroyAllWindows()

 

效果图:

局部代码图:

使用opencv识别种子,并标出种子的数量_第2张图片

 

全局的效果图:

使用opencv识别种子,并标出种子的数量_第3张图片

 

你可能感兴趣的:(opencv,opencv,计算机视觉,python)