计算图像中的对象

时间:2017-12-06 06:00:25

标签: python image-processing

我想用python计算图像中的对象数量 这是我的代码,但它只返回1 我正在使用轮廓在对象上绘制圆圈

import cv2
from matplotlib import pyplot as plt
import numpy as np 
kernel = np.ones((5,5), np.uint8)
img = cv2.imread('/home/mfp/Desktop/images/coins.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
mean = cv2.blur(gray , (7,7))
closing = cv2.morphologyEx(mean, cv2.MORPH_CLOSE, kernel)
opening = cv2.morphologyEx(closing, cv2.MORPH_OPEN, kernel)


ret, thresh = cv2.threshold(opening, 127, 255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
im2, contours, hierarchy =cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
i =0
for cnt in contours:
cv2.drawContours(img, [cnt], 0, (0, 0, 255), 3)
x, y, w, h = cv2.boundingRect(cnt)
if x>30 and x<60 and y>40 and y<80:
    i=i+1
    #cv2.rectangle(img, (x,y), (x+w,y+h), (0,0,255), 2)

elif x>60 and x<120 and y>80 and y<160:
    i=i+1
    #cv2.rectangle(img, (x,y), (x+w,y+h), (0,0,255), 2)
print(i)    


cv2.imshow('Threshold', thresh)
cv2.imshow('Image', img)

cv2.waitKey(0)
cv2.destroyAllWindows()

1 个答案:

答案 0 :(得分:0)

检查打开和关闭功能的结果,以查看对象是否因此过程而相互接触。这可能导致它们被连接并因此被识别为一个整体轮廓。此外,在绘制轮廓或执行任何其他操作之前,根据区域对轮廓进行排序。它有助于避免选择可能检测到的太小/太大的轮廓。需要您的输入样本图像进一步说明!