opencv2中的轮廓和凸包为阈值32 uint图像

时间:2015-05-18 15:39:34

标签: python opencv image-processing contour

我有以下代码:

    import cv2
    import numpy as np
    import matplotlib
    import matplotlib.pyplot as plt
    from skimage import data
    from skimage import filter
    from skimage.filter import threshold_otsu

    matplotlib.rcParams['font.size'] = 9

    nomeimg = 'frame1_depth.png'

    i = cv2.imread(nomeimg, -1)
    #conversione da 16 a 32 uint
    img = np.array(i, dtype=np.uint32)
    img *= 65536
    print img.dtype

    #thresholding con il metodo Otsu 
    thresh = threshold_otsu(img)
    binary = img > thresh
    print thresh

    plt.figure(1)
    fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(8, 2.5))
    ax1.imshow(img)
    ax1.set_title('Original')
    ax1.axis('off')

    ax2.hist(img)
    ax2.set_title('Histogram')
    ax2.axvline(x=thresh, color='r', linestyle='dashed', linewidth=2)

    ax3.imshow(binary, cmap=plt.cm.gray)
    ax3.set_title('Thresholded')
    ax3.axis('off')

    plt.figure(2)
    f, ax = plt.subplots(figsize=(8, 2.5))
    ax.imshow(binary, cmap=plt.cm.gray)
    ax.set_title('Thresholded')
    ax.axis('off')

    plt.show()

我有一组来自XBOX kinect的深度图像,因此在数据类型转换后我可以使用一些仅适用于8或32位图像的opencv函数,我已经设定了阈值使用Otsu算法的图像并显示结果。

我已经获得了一个子图,其中我有原始图像,直方图和阈值黑白图像。现在我只想在这个黑白图像上工作,我想保存它并计算轮廓,凸包和其他几何特征。但是,它只是阈值,但otsu

我该如何计算?

1 个答案:

答案 0 :(得分:4)

如果您想使用二进制图片处理OpenCV中的findContours和其他图像处理分析功能,只需将binary转换为uint8即可。此外,请确保缩放图像,使非零值变为255. uint32仅在某些模式下工作,并且为了避免在记住哪些模式允许您执行此操作的模式时出现任何不必要的麻烦,坚持uint8

同样,这样做:

binary = 255*(binary.astype('uint8'))

完成转换后,您可以拨打findContours

contours, hierarchy = cv2.findContours(binary,cv2.RETR_LIST,cv2.CHAIN_APPROX_NONE)

以上只是调用它的一种方法。我建议您查看文档以获取更多详细信息,我已将其链接到上面。

另一个例子,如果你想找到你的阈值图像的凸包,它有一堆形状通过convexHull,你需要一组代表你的轮廓的点,这完全由contours的{​​{1}}输出。但是,cv2.findContours函数假定只有一个单个对象表示一个轮廓。如果您有多个对象,因此有多个对象,则必须遍历每个轮廓并存储结果。

因此,做这样的事情:

convexHull

hull = [cv2.convexHull(cnt) for cnt in contours] 中的每个元素都将返回由每个轮廓构成凸包的坐标。因此,要访问轮廓hull的凸包的坐标,您可以这样做:

i
顺便说一下,这里有几个很棒的链接,可以帮助您开始使用OpenCV的形状分析功能。这是一个链接,讨论如何在更一般的背景下使用points = hull[i]

http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_imgproc/py_contours/py_contours_begin/py_contours_begin.html

这是另一个关于OpenCV其他形状分析功能的链接,例如凸包,图像时刻等:

http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_imgproc/py_contours/py_contour_features/py_contour_features.html

玩得开心!

相关问题