Python 如何提高我的爪子检测能力?
在我上一个关于的问题之后,我开始加载其他测量值,看看它能保持多久。不幸的是,我很快就遇到了前面步骤之一的问题:识别爪子 你看,我的概念验证基本上是利用每个传感器随时间变化的最大压力,开始寻找每行的总和,直到找到为止!=0.0. 然后,它对列执行相同的操作,并且一旦它找到两个以上的行,这些行再次为零。它将最小和最大的行和列值存储到某个索引中 如图所示,这在大多数情况下都非常有效。然而,这种方法有很多缺点(除了非常原始):Python 如何提高我的爪子检测能力?,python,image-processing,Python,Image Processing,在我上一个关于的问题之后,我开始加载其他测量值,看看它能保持多久。不幸的是,我很快就遇到了前面步骤之一的问题:识别爪子 你看,我的概念验证基本上是利用每个传感器随时间变化的最大压力,开始寻找每行的总和,直到找到为止!=0.0. 然后,它对列执行相同的操作,并且一旦它找到两个以上的行,这些行再次为零。它将最小和最大的行和列值存储到某个索引中 如图所示,这在大多数情况下都非常有效。然而,这种方法有很多缺点(除了非常原始): 人类可以有“空心脚”,这意味着脚印本身有几排空的。因为我担心这种情况也会
- 人类可以有“空心脚”,这意味着脚印本身有几排空的。因为我担心这种情况也会发生在(大型)狗身上,所以我在切断爪子之前至少要等两三排空狗 如果在到达多个空行之前在另一列中创建了另一个联系人,则会产生问题,从而扩大该区域。我想我可以比较一下这些列,看看它们是否超过某个值,它们一定是分开的爪子
- 当狗很小或以更高的速度行走时,问题会变得更严重。发生的情况是,前爪的脚趾仍在接触,而后爪的脚趾只是在与前爪相同的区域内开始接触 使用我的简单脚本,它将无法分割这两个帧,因为它必须确定该区域的哪些帧属于哪个paw,而当前我只需要查看所有帧的最大值
我的公共Dropbox文件夹(,)中有我在问题设置中使用的测量值。为了让您了解最新信息:-)我不是图像检测方面的专家,我也不懂Python,但我会尝试一下 要检测单个爪子,您应该首先只选择压力大于某个小阈值、非常接近无压力的所有东西。上面的每个像素/点都应该被“标记”。然后,与所有“标记”像素相邻的每个像素都被标记,并且这个过程重复几次。将形成完全相连的质量,因此有不同的对象。然后,每个“对象”都有一个最小和最大的x和y值,因此边界框可以整齐地围绕在它们周围 伪代码:
(标记)高于(0.5)的所有像素
(标记)与(标记)像素相邻的所有像素
重复(步骤2)(5)次
将每个完全连接的质量分离为单个对象
标记每个对象的边缘,并将其切割成切片。
那就差不多了 注意:我说的是像素,但这可能是使用像素平均值的区域。优化是另一个问题
听起来您需要分析每个像素的函数(随时间变化的压力),并确定(当它在另一个方向上改变>X时,它被认为是一个计数器错误的转折点)
如果你知道它在哪一帧转动,你就会知道哪一帧压力最大,哪一帧压力最小。从理论上讲,你会知道爪子最用力按压的两帧,并能计算出这些间隔的平均值
之后,我将开始决定它是哪只爪子的问题
这和以前一样,知道每个爪子何时施加最大压力有助于您做出决定。如果您只是想要(半)连续区域,Python模块中已经有了一个简单的实现。这是一种相当常见的操作
基本上,您有5个步骤:
def find_paws(data, smooth_radius=5, threshold=0.0001):
data = sp.ndimage.uniform_filter(data, smooth_radius)
thresh = data > threshold
filled = sp.ndimage.morphology.binary_fill_holes(thresh)
coded_paws, num_paws = sp.ndimage.label(filled)
data_slices = sp.ndimage.find_objects(coded_paws)
return object_slices
结构
kwarg转换为各种scipy.ndimage.morphology
函数)会更有效,但由于某些原因,这并不能正常工作……)thresh=data>value
)的位置具有布尔数组filled=sp.ndimage.morphics.binary\u Fill\u holes(thresh)
)coded\u paws,num\u paws=sp.ndimage.label(filled)
)。这将返回一个数组,其中区域按数字编码(每个区域是唯一整数(1到paw数)的连续区域,其他所有区域均为零)data\u slices=sp.ndimage.find\u对象(已编码的爪子)
隔离相邻区域。这将返回slice
对象的元组列表,因此可以获得
import numpy as np
import scipy as sp
import scipy.ndimage
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
def animate(input_filename):
"""Detects paws and animates the position and raw data of each frame
in the input file"""
# With matplotlib, it's much, much faster to just update the properties
# of a display object than it is to create a new one, so we'll just update
# the data and position of the same objects throughout this animation...
infile = paw_file(input_filename)
# Since we're making an animation with matplotlib, we need
# ion() instead of show()...
plt.ion()
fig = plt.figure()
ax = fig.add_subplot(111)
fig.suptitle(input_filename)
# Make an image based on the first frame that we'll update later
# (The first frame is never actually displayed)
im = ax.imshow(infile.next()[1])
# Make 4 rectangles that we can later move to the position of each paw
rects = [Rectangle((0,0), 1,1, fc='none', ec='red') for i in range(4)]
[ax.add_patch(rect) for rect in rects]
title = ax.set_title('Time 0.0 ms')
# Process and display each frame
for time, frame in infile:
paw_slices = find_paws(frame)
# Hide any rectangles that might be visible
[rect.set_visible(False) for rect in rects]
# Set the position and size of a rectangle for each paw and display it
for slice, rect in zip(paw_slices, rects):
dy, dx = slice
rect.set_xy((dx.start, dy.start))
rect.set_width(dx.stop - dx.start + 1)
rect.set_height(dy.stop - dy.start + 1)
rect.set_visible(True)
# Update the image data and title of the plot
title.set_text('Time %0.2f ms' % time)
im.set_data(frame)
im.set_clim([frame.min(), frame.max()])
fig.canvas.draw()
def find_paws(data, smooth_radius=5, threshold=0.0001):
"""Detects and isolates contiguous regions in the input array"""
# Blur the input data a bit so the paws have a continous footprint
data = sp.ndimage.uniform_filter(data, smooth_radius)
# Threshold the blurred data (this needs to be a bit > 0 due to the blur)
thresh = data > threshold
# Fill any interior holes in the paws to get cleaner regions...
filled = sp.ndimage.morphology.binary_fill_holes(thresh)
# Label each contiguous paw
coded_paws, num_paws = sp.ndimage.label(filled)
# Isolate the extent of each paw
data_slices = sp.ndimage.find_objects(coded_paws)
return data_slices
def paw_file(filename):
"""Returns a iterator that yields the time and data in each frame
The infile is an ascii file of timesteps formatted similar to this:
Frame 0 (0.00 ms)
0.0 0.0 0.0
0.0 0.0 0.0
Frame 1 (0.53 ms)
0.0 0.0 0.0
0.0 0.0 0.0
...
"""
with open(filename) as infile:
while True:
try:
time, data = read_frame(infile)
yield time, data
except StopIteration:
break
def read_frame(infile):
"""Reads a frame from the infile."""
frame_header = infile.next().strip().split()
time = float(frame_header[-2][1:])
data = []
while True:
line = infile.next().strip().split()
if line == []:
break
data.append(line)
return time, np.array(data, dtype=np.float)
if __name__ == '__main__':
animate('Overlapping paws.bin')
animate('Grouped up paws.bin')
animate('Normal measurement.bin')
# This uses functions (and imports) in the previous code example!!
def paw_regions(infile):
# Read in and stack all data together into a 3D array
data, time = [], []
for t, frame in paw_file(infile):
time.append(t)
data.append(frame)
data = np.dstack(data)
time = np.asarray(time)
# Find and label the paw impacts
data_slices, coded_paws = find_paws(data, smooth_radius=4)
# Sort by time of initial paw impact... This way we can determine which
# paws are which relative to the first paw with a simple modulo 4.
# (Assuming a 4-legged dog, where all 4 paws contacted the sensor)
data_slices.sort(key=lambda dat_slice: dat_slice[2].start)
# Plot up a simple analysis
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
annotate_paw_prints(time, data, data_slices, ax=ax1)
ax2 = fig.add_subplot(2,1,2)
plot_paw_impacts(time, data_slices, ax=ax2)
fig.suptitle(infile)
def plot_paw_impacts(time, data_slices, ax=None):
if ax is None:
ax = plt.gca()
# Group impacts by paw...
for i, dat_slice in enumerate(data_slices):
dx, dy, dt = dat_slice
paw = i%4 + 1
# Draw a bar over the time interval where each paw is in contact
ax.barh(bottom=paw, width=time[dt].ptp(), height=0.2,
left=time[dt].min(), align='center', color='red')
ax.set_yticks(range(1, 5))
ax.set_yticklabels(['Paw 1', 'Paw 2', 'Paw 3', 'Paw 4'])
ax.set_xlabel('Time (ms) Since Beginning of Experiment')
ax.yaxis.grid(True)
ax.set_title('Periods of Paw Contact')
def annotate_paw_prints(time, data, data_slices, ax=None):
if ax is None:
ax = plt.gca()
# Display all paw impacts (sum over time)
ax.imshow(data.sum(axis=2).T)
# Annotate each impact with which paw it is
# (Relative to the first paw to hit the sensor)
x, y = [], []
for i, region in enumerate(data_slices):
dx, dy, dz = region
# Get x,y center of slice...
x0 = 0.5 * (dx.start + dx.stop)
y0 = 0.5 * (dy.start + dy.stop)
x.append(x0); y.append(y0)
# Annotate the paw impacts
ax.annotate('Paw %i' % (i%4 +1), (x0, y0),
color='red', ha='center', va='bottom')
# Plot line connecting paw impacts
ax.plot(x,y, '-wo')
ax.axis('image')
ax.set_title('Order of Steps')