【发布时间】:2019-10-24 04:09:51
【问题描述】:
我想从上面数这张图片上的树数。
我知道如何计算元素,但直到现在我使用的是白色背景的图像,所以计数要容易得多。但是在这样的图像上我不知道该怎么做:
我把图像转成灰色,然后做了阈值*(阈值是手工做的,有没有办法自动找到?),我的下一个想法是找到黑点的“中心”,或者将它们“分组”。
我也尝试改变亮度和对比度,但没有奏效。
我该怎么办? 这是我写的代码:
import cv2
import numpy as np
# Read image
img = cv2.imread('slika.jpg')
# Convert image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Show grayscale image
cv2.imshow('gray image', gray)
cv2.waitKey(0)
#BIG PROBLEM: IM FINDING VALUE OF `40` IN THE LINE BELOW MANUALLY
# Inverse binary threshold image with threshold at 40,
_, threshold_one = cv2.threshold(gray, 40 , 255, cv2.THRESH_BINARY_INV)
# Show thresholded image
cv2.imshow('threshold image', threshold_one)
cv2.waitKey(0)
# Find contours
contours, h = cv2.findContours(threshold_one, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
print('Number of trees found:', len(contours)) #GIVES WRONG RESULT
# Iterate all found contours
for cnt in contours:
# Draw contour in original/final image
cv2.drawContours(img, [cnt], 0, (0, 0, 255), 1)
# Show final image
cv2.imshow('result image', img)
cv2.waitKey(0)
这是有阈值的图像,我尝试过模糊它(为了连接黑点),但最终输出是一样的:
这是结果图片:
【问题讨论】:
-
这是个难题,这里不能全面回答,见e.g. towardsdatascience.com/…
标签: python opencv computer-vision