如果单个图像中有多个 ROI,如何计算每个单独 ROI 的 RGB 平均值?

问题描述 投票:0回答:1

我有一张 RGB 格式的 3 通道图像,其中包含许多建筑物作为感兴趣区域。图像的背景是全黑的(零像素)。我尝试计算每个单独 ROI 的颜色特征,并将它们保存在 CSV 文件中,但我的代码仅将单个 RGB 值作为每个通道的平均值,因为我需要保存 R、G、B 和 RGB 平均值CSV 文件中的每个 ROI。任何指导将不胜感激。 enter image description here

import numpy as np
import pandas as pd
from skimage import io

image = io.imread("/content/drive/MyDrive/277.png")

current_roi = 1
start_pixel = None
roi_mean_values = []

for y in range(image.shape[0]):
for x in range(image.shape[1]):

pixel_value = image[y, x]

     if np.any(pixel_value > 0):  
           if start_pixel is None:
                 start_pixel = (x, y)
           elif start_pixel is not None:
               end_pixel = (x - 1, y)  # End of the current ROI
               roi = image[start_pixel[1]:end_pixel[1] + 1, start_pixel[0]:end_pixel[0] + 1]
    
               mean_rgb = np.mean(roi, axis=(0, 1))
               roi_mean_values.append({'ROI': current_roi,
                                    'Mean_R': mean_rgb[0],
                                    'Mean_G': mean_rgb[1],
                                    'Mean_B': mean_rgb[2]})
    
              current_roi += 1
              start_pixel = None

roi_mean_df = pd.DataFrame(roi_mean_values)

roi_mean_df.to_csv("roi_mean_values.csv", index=False)

print("RGB mean values for individual buildings (ROIs) saved to 'roi_mean_values.csv'.")
python numpy image-processing image-segmentation scikit-image
1个回答
0
投票

据我了解,投资回报率是由输入图像的“连接组件”给出的。每个连接的组件都是一个 ROI。 您可以在不迭代 ROI 的情况下解决这个问题,如果有很多 ROI,这可能会变得相当昂贵。不过,这段代码确实显式地迭代了像素,这在 Python 中很慢。也许,迭代 ROI 并使用编译函数处理所有像素会产生更快的 Python 代码,尽管实际上正在完成更多的工作。但是用编译语言编写的该算法是您可以编写的最有效的算法。

import numpy as np import skimage image = skimage.io.imread("/Users/cris/Downloads/G4IXb.png") n_channels = image.shape[2] # Find binary image separating background and objects mask = np.any(image > 0, axis=2) # Label this mask image, each ROI gets a unique label lab, n_labs = skimage.measure.label(mask, return_num=True) # Create arrays where we'll collect the information sum = np.zeros((n_labs + 1, n_channels)) number = np.zeros(n_labs + 1) # Loop over all pixels. for ii in range(image.shape[0]): for jj in range(image.shape[1]): # For each pixel, look at the label, and add information to # the arrays for that label. index = lab[ii, jj] sum[index, :] += image[ii, jj, :] number[index] += 1 # We're done. The mean color is the sum divided by the number of pixels. mean_colors = sum / number[:, None]

让我们看看平均颜色是什么样的:

# Paint an image with the mean colors mean_colors = np.round(mean_colors).astype(np.uint8) out = np.empty_like(image) for ii in range(image.shape[0]): for jj in range(image.shape[1]): out[ii, jj] = mean_colors[lab[ii, jj]] import matplotlib.pyplot as plt plt.subplot(1, 2, 1) plt.imshow(image) plt.subplot(1, 2, 2) plt.imshow(out) plt.show()

© www.soinside.com 2019 - 2024. All rights reserved.