从1000个图像池中读取50个图像作为每个像素矩阵

2024-06-06 11:40:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有1000个灰度图像,尺寸为800x600像素。 每个像素的值介于0…255之间

我想从这1000张图片中选出50张。 在这50幅图像中,我想找出最大灰度值(0…255)。 基于此,我只想构建一个最大grascale值(0…255)的新图像

最后,我想从1000幅图像中取出每一幅,将每个像素除以新的图像像素,然后乘以255

我从选择前50张拾取的图像开始:

from random import seed
from random import sample

# seed random number generator
seed(1)
# prepare a sequence
sequence = [i for i in range(1000)]
print(sequence)
# select a subset without replacement
subset = sample(sequence, 50)
                print("Chosed 50 random images: ", subset)

然后我开始读循环中的图像。 从50张拾取的图像中读取最大像素值:

for i in range(0,49):
       for d in range(0, 599):
             for s in range(0, 799):
                      print("Chosed image: ", subset[i], "Chosed pixel (rundownstairs): ", d, "Chosed pixel (run sidewise): ", s )   

但我不知道如何读取矩阵中的像素并进行数学矩阵计算


Tags: sampleinfrom图像importforrangerandom
2条回答

对于图像处理,我建议您opencv,您必须安装它。要读取灰度图像,您可以使用此选项,您将获得一个numpy数组:

import cv2
import numpy as np


img = cv2.imread('image_file_path', 0)

要查找数组中的最大值,可以使用以下方法:

max_value = np.max(img)

要将数学运算应用于整个数组,只需执行以下操作:

mod_img = img / max_value

由于我没有你的图像,我生成了n个随机图像。 我用这些图像做了一个数组,并用max值找到了它们的坐标。然后我组织了这些索引以便可以读取: 使用listOfCordinates您应该能够开始对像素进行操作。 注意,我使用了numpy,我不知道这是否是一个问题

import numpy as np
import cv2
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import glob, os

os.chdir("C:/Users\iareval1\Documents\OCLASS\class_def") #your folder
n = 5 #Number oof images
img_arr = [] #array with images
n_nad_files = []

for i in range(0,n):
    n_nad_files.append(glob.glob("*.png")[np.random.randint(n)])

for file in n_nad_files: #set the file termination
    img = cv2.imread(file, 0)
    img_arr.append(img)



dim_x = img_arr[0].shape[0]
dim_y = img_arr[0].shape[1]

img_with_max = np.zeros((dim_x, dim_y))


cnt = 0
for image in img_arr:
    print("Max values in image " +  str(cnt))
    for x in range (0, dim_x):
        for y in range (0, dim_y):
            img_with_max[x][y] = max(img_with_max[x][y], image[x][y])
    cnt += 1


如果要打印图像,可以

plt.imshow(YOUR_IMAGE,cmap=cm.bone) #show your array with the selected colour
plt.show() #show the image

相关问题 更多 >