如何计算视频中钢棒的数量 [英] How to count the number of steel rods in a video

查看:134
本文介绍了如何计算视频中钢棒的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的图像中,我需要使用opencv在Python中计算钢棒的数量.

I need to count the number of steel rods , in Python using opencv for the following image.

以钢棒为中心的图像 我最初将图像转换为灰度,然后使用侵蚀功能,然后使用精边功能检测边缘,如下所示. 精巧边缘后的图像 后来找到轮廓,并使用边界旋转矩形对杆进行计数.我无法获得正确的计数.

Image with the steel rods at the center I have initially converted the image to grayscale,then used erode function followed with canny edge function to detect the edges as shown below. image after canny edge Later find contours and used bounding rotated rectangle to count the rods. I am not able to get the correct count.

kernel = np.ones((4,4),np.uint8)
erosion = cv2.erode(gray,kernel,iterations = 1)
cv2.imshow('Erode',erosion)
canny=cv2.Canny(erosion,100,200)
cv2.imshow('Canny',canny)
kernele=np.array([[0,1,1,0],[0,1,1,0],[0,1,1,0],[0,1,1,0]],np.uint8)
dilation = cv2.dilate(canny,kernele,iterations = 1)
cv2.imshow('dilate',dilation)
c,cnt,h=cv2.findContours(dilation,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
if cnt:
    i=0
    for cnt in contours:
        rect = cv2.minAreaRect(cnt)
        box = cv2.boxPoints(rect)
        box = np.int0(box)
        if rect[1][0]>1 and rect[1][0]<15:  #width of rod
           i+=1

请提出修改内容或获取计数的建议. 谢谢

Kindly suggest what to modify or how to get the count. Thank You

下一张图片

推荐答案

您可以尝试使用这种替代方法,而不是先查找边缘然后按宽度进行查找.

Instead of finding edges and then going by width, there is this alternative way that you can try.

我假设您的图像设置是恒定的,因此可以裁剪包含杆的区域(否则将非常困难).

I assume your image setup is constant and hence you can crop the region containing the rods (it would be very difficult otherwise).

以适当的大小和常数自适应地调整图像阈值.

Adaptive threshold the image with appropriate size and constant.

然后在图像中选择100条随机行,并计算图像中黑色或白色条的数量.

Then choose 100 random rows in the image and count the number of black or white strips in it.

找到这100行的中位数,并减去适当的条件以消除错误的边界计数(第一个标尺之前和最后一个标尺之后的白色带)

Find the median of these 100 rows and subtract an appropriate condition to eliminate the wrong border counts (the white strip before the first rod and after the last rod)

代码:

import cv2
import numpy as np
from random import randint
from itertools import groupby

img = cv2.imread('img.jpg',0)
rod_count = []
rows, cols =img.shape[:2]
th2 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,\
                    cv2.THRESH_BINARY,11, 2)

count = 100
while( count!=0 ):

    count = count-1
    random_row = randint(0, rows-1)

    arr = th2[random_row:random_row+1, :]
    arr2 = np.array(arr)[0].tolist()
    temp = [a[0] for a in groupby(arr2)]
    b = sum(x == 0 for x in temp)
    rod_count.append(b)


print np.median(rod_count)-2

输出: 15

这篇关于如何计算视频中钢棒的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆