将图像转换为Python中的2D坐标数组,以进行两点关联

时间:2015-02-06 19:47:43

标签: python opencv numpy fft correlation

我需要从astroML Python module执行两点关联功能,我的数据最初是jpg图像,黑白,我使用OpenCV image thresholding将其转换为二进制图像(不确定我做了什么)对的)。问题是现在我如何将2D二进制矩阵或1和0转换为只有1的坐标列表。基本代码行是这个:

import numpy as np
import cv2
from astroML.correlation import two_point
import matplotlib.pyplot as plt

im_normal = cv2.imread('example.jpg')
im_gray = cv2.imread('example.jpg', cv2.CV_LOAD_IMAGE_GRAYSCALE)
(thresh, im_bw) = cv2.threshold(im_gray, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)

我是否必须遍历矩阵的所有单元格,并拉出坐标或者是否有一种简单的方法可以做到这一点?

我想要进行分析的图像 - enter image description here

1 个答案:

答案 0 :(得分:2)

是的,就像我想通过循环遍历阵列所做的大多数事情一样:numpy有一个内置的解决方案。

[numpy.nonzero][1]

numpy.nonzero(a)
Return the indices of the elements that are non-zero.

    Returns a tuple of arrays, one for each dimension of a, containing the indices of the non-zero elements in that dimension. The corresponding non-zero values can be obtained with:

    `a[nonzero(a)]`

    To group the indices by element, rather than dimension, use:

    `transpose(nonzero(a))`

    The result of this is always a 2-D array, with a row for each non-zero element.

代码示例:

>>> x = np.eye(3)
>>> x
array([[ 1.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.]])
>>> np.nonzero(x)
(array([0, 1, 2]), array([0, 1, 2]))