将图像转换为 Python 中的二维坐标数组以进行两点相关
Convert an image to a 2D array of coordinates in Python for two point correlation
我需要从 astroML Python module, my data is originally a jpg image, black and white, and I convert it to binary image using OpenCV image thresholding 执行两点相关函数(不确定我做对了)。问题是现在我如何将 2D 二进制矩阵或 ones 和 zeros 转换为只有 ones 的坐标列表。基本代码行是这一行:
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)
我是否必须遍历矩阵的所有单元格并拉出坐标,或者是否有简单的 numpy 方法来做到这一点?
我要对其执行分析的图像 -
是的,就像我想通过遍历数组来完成的大多数事情一样: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]))
我需要从 astroML Python module, my data is originally a jpg image, black and white, and I convert it to binary image using OpenCV image thresholding 执行两点相关函数(不确定我做对了)。问题是现在我如何将 2D 二进制矩阵或 ones 和 zeros 转换为只有 ones 的坐标列表。基本代码行是这一行:
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)
我是否必须遍历矩阵的所有单元格并拉出坐标,或者是否有简单的 numpy 方法来做到这一点?
我要对其执行分析的图像 -
是的,就像我想通过遍历数组来完成的大多数事情一样: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]))