|
发表于 2020-12-17 19:04:04
|
显示全部楼层
本楼为最佳答案
本帖最后由 YunGuo 于 2020-12-17 20:32 编辑
你这张图我可以用这个方式,这个仅可统计黄色菱形数量。对opencv不是很熟悉,可能还有其它方法。import cv2
import numpy as np
img = cv2.imread('image.jpg')
# 图像去噪
img = cv2.fastNlMeansDenoisingColored(img, None, 10, 10, 7, 21)
# BGR转HSV
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# HSV黄色min值
low_hsv = np.array([26, 43, 46])
# HSV黄色max值
upp_hsv = np.array([34, 255, 255])
# 提取掩膜
mask = cv2.inRange(hsv, lowerb=low_hsv, upperb=upp_hsv)
# 保存掩模后图片
cv2.imwrite('huang.jpg', mask)
img1 = cv2.imread('huang.jpg')
# 转灰度图片
imgray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
# 获取白色图形轮廓
ret, thresh = cv2.threshold(imgray, 127, 255, 0)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 根据图形面积计算图形数量
count = 0
for cnt in contours:
# 获取每个图形面积
area = cv2.contourArea(cnt)
if 2700 <= area <= 3000:
count += 1
elif area >= 3000:
num = int(area / 2720)
count += num
print(count)
对代码优化了一下,可以统计出图中三种颜色的菱形分别是多少个import cv2
import numpy as np
def hsv_img(img, color):
image1 = cv2.imread(img)
# 图像去噪
image1 = cv2.fastNlMeansDenoisingColored(image1, None, 10, 10, 7, 21)
# BGR转HSV
hsv = cv2.cvtColor(image1, cv2.COLOR_BGR2HSV)
if color == "黄色":
# 当前颜色的hsv值
low_hsv = np.array([26, 43, 46])
upp_hsv = np.array([34, 255, 255])
# 黄色面积1600
area = 1600
# 处理图片
result = handle_img(area, hsv, low_hsv, upp_hsv)
print(f'{color}数量:', result)
elif color == "紫色":
low_hsv = np.array([125, 43, 46])
upp_hsv = np.array([155, 255, 255])
# 紫色面积1700
area = 1700
# 处理图片
result = handle_img(area, hsv, low_hsv, upp_hsv)
print(f'{color}数量:', result)
elif color == "绿色":
low_hsv = np.array([35, 43, 46])
upp_hsv = np.array([77, 255, 255])
# 绿色面积1900
area = 1900
# 处理图片
result = handle_img(area, hsv, low_hsv, upp_hsv)
print(f'{color}数量:', result)
def handle_img(area, hsv, low, upp):
# 提取掩膜
mask = cv2.inRange(hsv, lowerb=low, upperb=upp)
# 保存掩模后图片
cv2.imwrite('mask.jpg', mask)
img1 = cv2.imread('mask.jpg')
# 转灰度图片
imgray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
# 对图形进行侵蚀,分离相连的图形
kernel = np.ones((5, 5), np.uint8)
erosion = cv2.erode(imgray, kernel, iterations=2)
# 获取白色图形轮廓
ret, thresh = cv2.threshold(erosion, 127, 255, 0)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 根据图形面积统计图形数量
count = 0
for cnt in contours:
# 获取每个图形面积
area1 = cv2.contourArea(cnt)
if area1 >= area:
count += 1
return count
if __name__ == '__main__':
image = 'image.jpg'
hsv_img(image, '黄色')
hsv_img(image, '紫色')
hsv_img(image, '绿色')
|
|