-1

我试图从数据库的每个图像中获取 5 个连续像素,并将它们连续定位以创建 250x250px 的新图像。数据库中的所有图像都是 250x250px。我得到的 Numpy 数组中只有 250 个项目,尽管数据库中有大约 13,000 张照片。有人可以帮我发现问题吗?

'len(new_img_pxl)' 的当前输出 = 250

插图

#edit:        
from imutils import paths
import cv2
import numpy as np

# access database
database_path = list(paths.list_images('database'))

#grey scale database
img_gray = []

x = -5
y = 0
r = 0

new_img_pxl = []

# open as grayscale, resize
for img_path in database_path:
    img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)
    img_resize = cv2.resize(img, (250, 250))
    img_gray.append(img_resize)


# take five consecutive pixel from each image
for item in img_gray:
    x += 5
    y += 5
    five_pix = item[[r][x:y]]
    for pix in five_pix:
        new_img_pxl.append(pix)
    if y == 250:
        r += 1
        x = -5
        y = 0



# convert to array
new_img_pxl_array = np.array(new_img_pxl)
reshape_new_img = new_img_pxl_array.reshape(25,10)



# Convert the pixels into an array using numpy
array = np.array(reshape_new_img, dtype=np.uint8)
new_img_output = cv2.imwrite('new_output_save/001.png',reshape_new_img)
4

1 回答 1

0

您的错误在第二个循环中。

for item in img_gray:

对于列表 img_gray 中的每个图像 (i),您执行以下操作:

for a in item:

对于图像 (i) 中的每一行 (j),提取 5 个像素并将它们附加到 new_img_pxl。

第一个错误是您不只从每张图像中提取 5 个像素,而是从每张图像的每一行中提取 5 个像素。

您的第二个错误是在提取 250 个像素后,变量 x 和 y 的值高于 250(行的长度)。结果,当您尝试访问像素 [250:255] 等时,您会得到“无”。

如果我理解您的意图,那么您应该实施的方式如下:

r = 0
# As Mark Setchell suggested, you might want to change iterating 
# over a list of images to iterating over the list of paths
# for img_path in database_path:
for item in img_gray:
    # As Mark Setchell suggested, you might wat to load and
    # process your image here, overwriting the past image and         
    # having the memory released
    x += 5
    y += 5
    # when you finish a row jump to the next?
    if x==250:
        x = 0
        y = 5
        r+=1
    # not sure what you wanna do when you get to the end of the image. 
    # roll back to the start?
    if r==249 && x==250:
        r = 0
        x = 0
        y = 5
    five_pix = a[r, x:y]
    for pix in five_pix:
        new_img_pxl.append(pix)
于 2021-11-03T09:24:23.003 回答