【问题标题】:Processing pixel value of images in which pixel's coordinates are from list of lines处理像素坐标来自行列表的图像的像素值
【发布时间】:2021-08-09 22:12:55
【问题描述】:

我正在从事图像处理(python3)的任务,希望能找到算法的改进。我的任务有 2 个主要规格:

  • 3 幅灰度图像(大小相同,命名为 A、B、C)
  • 直线坐标列表(numpy数组)((x,y)是一个点的坐标)
[[x1 y1 x2 y2]

...

[x1n y1n x2n y2n]]

处理步骤:

  1. 将一条线的所有像素坐标放入一个列表(x_i,y_i)
  2. 获取坐标(x_i,y_i)对应的每3幅图像(A,B,C)的像素值(p_x,p_y)。将所有值 (p_x, p_y) 相加(分别为 A, B, C),然后我有 (scoreA, scoreB, scoreC)
  3. 在某些条件下测试(scoreA、scoreB、scoreC),如果不满足则忽略该行。
  4. 用其他行重复这些步骤。

目前,我的想法是创建一个名为“line_obj”的类来存储线路信息。

class line_obj:
    def __init__(self, x1, y1, x2, y2):
        self.x1 = x1
        self.y1 = y1
        self.x2 = x2
        self.y2 = y2
        self.scoreA = 0.0
        self.scoreB = 0.0     
        self.scoreC = 0.0   

然后我创建一个 line_obj(s) 列表,其中包含每一行的信息。之后,我对上述所有任务使用 for 循环。

for line_obj in line_obj_list:
  #line() method from scikit-image library to retrieve pixel coordinates of a line
    rr, cc = line(line_obj.y1, line_obj.x1, line_obj.y2, line_obj.x2)
    line_obj.scoreA = A[rr,cc].sum()
    line_obj.scoreB = B[rr,cc].sum()
    line_obj.scoreC = C[rr,cc].sum()

对于这个任务,我需要让它尽可能快,不确定它是否被优化。你能给我一个更好的主意吗?谢谢你。

【问题讨论】:

  • 一个简单的解决方案是在黑色背景上将每一行设置为与图像大小相同的白色。这成为一个掩码,可用于列出每个图像中掩码为白色(或非零)的所有值。
  • @fmw42 我担心在黑色图像上画白线作为蒙版需要更多的计算。我发现 line() 函数非常简单,因为它在一行中准确返回像素坐标(我认为在该掩码上绘制掩码和 np.where 更快)。
  • 但是你必须随机访问图像以获得每个点值。使用掩码和 Numpy,您可以进行矢量化操作。但我让你来测试你想要的速度。

标签: python numpy opencv image-processing scikit-image


【解决方案1】:

我实际上不了解您的坐标数据的结构。你说这是一个 numpy 数组,但你写的是一个平面坐标列表。不管是什么,最好将其转换为numpy。 如果想象你有以下数据:

import numpy as np
A = np.random.randint(0, 255, (1024, 1024)) #1024 is just example pic size
B = np.random.randint(0, 255, (1024, 1024)) #1024 is just example pic size
C = np.random.randint(0, 255, (1024, 1024)) #1024 is just example pic size

coords = np.random.randint(0, 1023, (200, 4)) #assuming you have 200*2 coords or whatever size the scikit outputs 
#Here I'm assuming x is the rows and y is columns  
A_pix_values_c1 = A[coords[:, 0], coords[: , 1]]  #c1 is coords 1
A_pix_values_c2 = A[coords[:, 2], coords[: , 3]]  #c2 is coords 2
B_pix_values_c1 = B[coords[:, 0], coords[: , 1]]
B_pix_values_c2 = B[coords[:, 2], coords[: , 3]]
C_pix_values_c1 = C[coords[:, 0], coords[: , 1]]
C_pix_values_c2 = C[coords[:, 2], coords[: , 3]]

现在我在猜测,因为我不太了解您要做什么。我假设您想对每张图像的两个坐标的像素值求和。

scoreA = A_pix_values_c1 + A_pix_values_c2
scoreB = B_pix_values_c1 + B_pix_values_c2
scoreC = C_pix_values_c1 + C_pix_values_c2

最好尽量避免循环。我对 scikit 图像不太熟悉,但是如果您可以一次将所有行放在一个数组中,最好这样做,然后应用上述方法,而不是循环遍历。 对于测试,您可以使用多种方式的 numpy 数组,例如

final_scoreA = scoreA[scoreA_condition]

【讨论】:

  • 谢谢。直线列表只是一条线的 2 个端点的列表。我的问题是获取像素坐标(line() 函数做了什么)。它返回一条线的 2 个点之间的像素坐标列表,如果我使用布尔索引,我可能会得到所有线的所有像素的坐标列表(我只需要每条线的 scoreA、B、C)。跨度>
  • 我正在考虑创建一个包含所有行的所有坐标的数组,这会产生一种大数组 (num_of_line, num_of_pixel_in_line,4)
猜你喜欢
  • 1970-01-01
  • 2023-04-04
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 2023-04-06
  • 1970-01-01
  • 1970-01-01
  • 2014-02-26
相关资源
最近更新 更多