Python爪印图像检测的实现与优化

假设我有一个传感器区域,上面有小猫在走,那么,如何用Python来识别小猫的爪子印呢?要知道爪子是走动的啊。

方法基本上是根据:随着时间推移得到每个传感器的最大压力,并且会开始寻找每行的总和,直到找到不为0的地方。然后,它对列执行相同的操作,一旦找到多于2行,那么它们再次为零。它将最小和最大行和列值存储到某些索引以便后面可以查找。
alt text
从图中可以看出,这在大多数情况下效果很好。然而,这种方法有很多缺点(除非是非常原始的实现):

  • 人类可以有“空心脚”,这意味着足迹本身有几排空行。同时,这可能发生在(大)狗身上,那么我们需要等待至少2或3个空行,然后切断爪子。
    如果另一个联系人在达到几个空行之前在另一列中进行了另一个联系,从而扩展了该区域,则会产生问题。我想我可以比较列,看看它们是否超过一定值,它们必须是分开的爪子。
  • 当狗很小或走得更高时,问题会变得更糟。发生什么事情是,前爪的脚趾仍然接触,而后爪的脚趾刚刚开始在与前爪相同的区域内接触!
    使用我的简单脚本,它将无法分割这两个,因为它必须确定该区域的哪个帧属于哪个爪子,而目前我只需要查看所有帧上的最大值。

开始出错的例子:
alt text alt text
所以现在我正在寻找一种更好的方式来识别和分离爪子(之后我会得到决定哪个爪子的问题!)。

alt text
coded_pa​​ws显示了所有不同的爪子,当应用于最大压力图像(见上文)时。然而,解决方案遍历每个框架(以分离重叠的爪子)并设置四个Rectangle属性,如坐标或高度/宽度。
我不知道如何把这些属性存储在一些可以应用于测量数据的变量中。因为我需要知道每个爪子,它的位置是什么,在哪个框架和夫妇这是哪个爪子(前/后,左/右)。
那么如何使用矩形属性来提取每个爪子的这些值?
在我的公共Dropbox文件夹(example 1example 2example 3)中的问题设置中使用了测量。

好了,问题描述清楚了,我们来看看怎么优化这个问题吧。

如果你只是想要(半)连续的区域,那么在Python中已经有一个简单的实现:SciPyndimage.morphology模块。这是一个相当普遍的image morphology操作。
基本上你有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
  1. 将输入数据模糊一点,以确保爪子具有连续的占位面积。 (使用更大的内核(structure kwarg到各种scipy.ndimage.morphology函数)会更有效),但是由于某些原因这不是正常工作…)
  2. 对阵列进行阈值,以便您具有压力超过某个阈值的位置的布尔数组(即thresh = data > value
  3. 填写任何内部孔,使您有更干净的区域(filled = sp.ndimage.morphology.binary_fill_holes(thresh)
  4. 找到单独的连续区域(coded_paws, num_paws = sp.ndimage.label(filled))。这将返回一个数组,区域由数字编码(每个区域是唯一整数的连续区域(1到爪数),其它地方为零))。
  5. 使用data_slices = sp.ndimage.find_objects(coded_paws)隔离连续区域。这将返回slice对象的元组列表,因此您可以使用[data[x] for x in data_slices]获取每个爪子的数据区域。相反,我们将绘制一个基于这些切片的矩形,这需要更多的工作。

下面的两个动画显示您的“重叠爪子”和“分组爪子”示例数据。这种方法似乎是完美的。 (无论什么值得,这运行比我的机器下面的GIF图像顺利,所以爪检测算法是相当快…)
Overlapping Paws Grouped Paws
这是一个完整的例子(现在有更详细的解释)。绝大多数是阅读输入和制作动画。实际的爪检测只有5行代码。

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')

 

为了确定哪个爪子在什么时候与传感器接触,最简单的解决方案是进行相同的分析,但是一次使用所有的数据。 (即将输入堆叠成一个3D阵列,并使用它,而不是单独的时间框架)。因为SciPy的ndimage功能是为了使用n维数组,所以我们不必修改原来的爪finding功能在所有

# 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')

alt text
alt text
alt text

 

By Code问答

Windows上NumPy的安装

Python的NumPy库

在机器学习中,会需要用到Python数据处理的NumPy库,通过pip在Windows上不能方便的安装NumPy, 那么怎样在windows上安装NumPy呢?

下载NumPy

在这里下载NumPy的安装包到本地,注意根据你的系统配置选择正确的安装版本:http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy

例如在windows 10的64位系统选择版本:numpy‑1.13.1+mkl‑cp36‑cp36m‑win_amd64.whl

安装NumPy

使用pip在本地安装,进入你所下载numpy安装包的路径,运行命令:

pip3 install numpy‑1.13.1+mkl‑cp36‑cp36m‑win_amd64.whl

By Code问答