scipy 找出图像上白点的位置

agyaoht7  于 2022-11-10  发布在  其他
关注(0)|答案(2)|浏览(137)
import matplotlib.image as img
import numpy as np
import matplotlib as plt
import matplotlib.pyplot as plt

image1 = img.imread("82.png",0)
image2 = img.imread("83.png",0)

diff = image2 - image1

matchingInd = np.where(diff > 0.6)

diff[matchingInd] = 1
plt.imshow(diff)

image1和image2的背景是黑色,但有一些亮点。image2与image1是同一张照片,但只是添加了一些亮点或删除了一些亮点。如何在image2上找到添加的亮点的位置?

3htmauhk

3htmauhk1#

因为你已经标记了OpenCV,我用下面的方法复制了你的问题。
考虑2个图像阵列ab,其中255是指亮点:

>>> a
array([[  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0],
       [  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0],
       [  0,   0, 255,   0, 255,   0,   0, 255,   0,   0,   0,   0,   0],
       [  0, 255,   0,   0,   0,   0,   0, 255,   0, 255, 255,   0,   0],
       [  0,   0,   0,   0,   0, 255,   0,   0,   0,   0,   0,   0,   0],
       [  0, 255,   0,   0,   0, 255, 255,   0, 255,   0,   0,   0,   0],
       [  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0]],
  dtype=uint8)

b中,与a相比,删除了一些斑点,并添加了新斑点:

>>> b
array([[  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 255, 255],
       [255,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 255],
       [255,   0, 255,   0, 255,   0,   0, 255,   0,   0,   0,   0,   0],
       [  0, 255,   0,   0,   0,   0,   0, 255,   0, 255,   0,   0,   0],
       [  0,   0,   0,   0,   0, 255,   0,   0,   0,   0, 255,   0,   0],
       [  0,   0,   0,   0,   0,   0,   0,   0, 255,   0, 255,   0,   0],
       [  0,   0,   0,   0,   0, 255,   0,   0,   0,   0,   0,   0,   0]],
  dtype=uint8)

使用cv2.subtract查找b中新添加的斑点。这应读作 * a中的元素从a中的元素中减去 *:

>>>diff = cv2.subtract(b, a)

diff仅包含新添加的斑点:

>>> diff
array([[  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 255, 255],
       [255,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 255],
       [255,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0],
       [  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0],
       [  0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 255,   0,   0],
       [  0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 255,   0,   0],
       [  0,   0,   0,   0,   0, 255,   0,   0,   0,   0,   0,   0,   0]],
  dtype=uint8)

现在使用np.argwhere找到上面提到的坐标:

>>> np.argwhere(diff == 255)
array([[ 0, 11],
       [ 0, 12],
       [ 1,  0],
       [ 1, 12],
       [ 2,  0],
       [ 4, 10],
       [ 5, 10],
       [ 6,  5]], dtype=int64)
5q4ezhmt

5q4ezhmt2#

您可以使用numpy.wherenumpy.argwhere
它们将给予相同的结果,但输出形状将有所不同:
numpy.where将为您提供一个包含两个元素的元组:所有x坐标(x1, x2, ...)的数组和所有y坐标(y1, y2, ...)的数组
numpy.argwhere将给予一个形状为(N,2)的数组,其中每行对应于一个像素的坐标

import numpy as np

my_array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

np.where(my_array < 4)
Out: (array([0, 0, 0]), array([0, 1, 2]))

np.argwhere(my_array < 4)
Out: array([[0, 0],
            [0, 1],
            [0, 2]])

注意:在尝试运行diff[matchingInd] = 1行时,使用np.argwhere应该会引发错误

相关问题