简体   繁体   English

计算对象的数量 OpenCV - Python

[英]Count the number of objects OpenCV - Python

This is my first project in Python(3.5.1) and OpenCV (3), so I'm sorry for my mistakes.这是我在 Python(3.5.1) 和 OpenCV (3) 中的第一个项目,所以我很抱歉我的错误。 I've some pictures like these ones: https://s12.postimg.org/ox8gw5l8d/gado.jpg我有一些像这样的图片: https : //s12.postimg.org/ox8gw5l8d/gado.jpg

I need to count how many white objects has on this image.我需要计算这张图片上有多少白色物体。 I tried to ise SimpleBlobDetector but I didn't work as I was expecting.我尝试使用 SimpleBlobDetector,但没有按预期工作。

# Standard imports
import cv2
import numpy as np;

# Read image
im = cv2.imread("C:/opencvTests/cattle.jpg", cv2.IMREAD_GRAYSCALE)

# Setup SimpleBlobDetector parameters.
params = cv2.SimpleBlobDetector_Params()

#filter by color
params.filterByColor = True
params.blobColor = 255

# Filter by Convexity
params.filterByConvexity = True
params.minConvexity = 0.87

# Filter by Inertia
params.filterByInertia = True
params.minInertiaRatio = 0.08

# Create a detector with the parameters
ver = (cv2.__version__).split('.')
if int(ver[0]) < 3 :
   detector = cv2.SimpleBlobDetector(params)
else : 
detector = cv2.SimpleBlobDetector_create(params)

# Detect blobs.
keypoints = detector.detect(im)

# Draw detected blobs as red circles.
# cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures the size of the circle        corresponds to the size of blob
im_with_keypoints = cv2.drawKeypoints(im, keypoints, np.array([]),   (0,0,255),     cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

# Show keypoints
cv2.imwrite("C:/opencvTests/blobSave.jpg",im_with_keypoints)
print("Total of objects")
print(len(keypoints))

Any help would be really appreciate!任何帮助将不胜感激! Thanks in advance提前致谢

Probably you will end up in wrong count if you continue working on this image.如果您继续处理此图像,可能最终会得到错误的计数。 Perform some pre-processing operations such as morphological operations to remove noise and also to separate the object from each other.执行一些预处理操作,例如形态学操作,以去除噪声并将对象彼此分离。 After this make use of "findcontours" an inbuilt opencv function.在此之后使用“findcontours”一个内置的opencv函数。 Then read the size of "findcontours" this will give the count of the objects.然后读取“findcontours”的大小,这将给出对象的数量。

I'm getting very close to the answer, I believe I just need to change some parameters according to the image.我已经非常接近答案了,我相信我只需要根据图像更改一些参数即可。 If someone needs something on this regard, this is my code:如果有人需要这方面的东西,这是我的代码:

# Standard imports
import cv2
import numpy as np;

# Read image
im = cv2.imread("C:/opencvTests/original.jpg", cv2.IMREAD_GRAYSCALE)

#Apply treshold
ret,im = cv2.threshold(im,240,255,cv2.THRESH_BINARY)

kernel = np.ones((6,6),np.uint8)
erosion = cv2.erode(im,kernel,iterations = 1)
opening = cv2.morphologyEx(im, cv2.MORPH_OPEN, kernel)
im = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, kernel)


# Setup SimpleBlobDetector parameters.
params = cv2.SimpleBlobDetector_Params()

#filter by color
params.filterByColor = True
params.blobColor = 255

# Filter by Convexity
params.filterByConvexity = True
params.minConvexity = 0.87

# Filter by Inertia
params.filterByInertia = True
params.minInertiaRatio = 0.08

# Create a detector with the parameters
ver = (cv2.__version__).split('.')
if int(ver[0]) < 3 :
    detector = cv2.SimpleBlobDetector(params)
else : 
    detector = cv2.SimpleBlobDetector_create(params)

# Detect blobs.
keypoints = detector.detect(im)

# Draw detected blobs as red circles.
# cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures the size of the circle        corresponds to the size of blob
im_with_keypoints = cv2.drawKeypoints(im, keypoints, np.array([]),   (0,0,255),     cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

# Show keypoints
cv2.imwrite("C:/opencvTests/keypoints.jpg",im_with_keypoints)
print("Total of objects")
print(len(keypoints))

Thank you very much!非常感谢!

I needed to implement the same logic.我需要实现相同的逻辑。 The task was to detect the number of houses from google map view.任务是从谷歌地图视图中检测房屋数量。

Read the image in greyscale Apply threshold Apply morphological operations for noise reduction using cv2.findContour() function, the blobs were counted读取灰度图像 应用阈值 使用 cv2.findContour() 函数应用形态学操作进行降噪,对斑点进行计数

Here's a part from the code which I wrote:这是我编写的代码的一部分:

img = cv2.imread("images/map_snippet2.png", 0)

ret, thresh = cv2.threshold(img, 242, 255, cv2.THRESH_TOZERO_INV)   # every pixel below the threshold is turned white
ret, thresh_final = cv2.threshold(thresh, 240, 255, cv2.THRESH_TOZERO)  # every pixel below the threshold is turned black
# using the above 2 lines, we only took values in range [240, 242]

# applying morphological operaations to reduce noise
kernel = np.ones((3,3), np.uint8)
morph_img = cv2.erode(thresh_final, kernel, iterations=1)

# using findContours() function to count the white blobs. 
# using this function on morph_img is better than using it on canny_img

blob, hierarchy = cv2.findContours(morph_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
blob_count = len(blob)

plt.imshow(morph_img, 'gray')   # this will count the number of white blobs in the images
plt.xlabel("Count = " + str(blob_count))
plt.ylabel("Detecting # of blobs")

plt.show()

Hope it helps希望它有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM