【发布时间】:2021-12-17 15:53:39
【问题描述】:
我正在尝试从数据库的每个图像中获取 5 个连续像素,并将它们连续定位以创建 250x250 像素的新图像。数据库中的所有图像都是 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)
【问题讨论】:
-
嗯...这里有几个问题需要考虑。 1)你为什么不必要地混合 OpenCV 和 PIL - 你会混淆自己。只用一个。 2)如果您只需要灰度图像,不要以彩色打开它们并进行转换,只需将它们打开为灰度并节省内存,即
grey = cv2.imread(..., cv2.IMREAD_GRAYSCALE)3)您为什么要在内存中列出13,000张图像? ?那是 800MB 的 RAM。打开 1 张图片,获取您想要的 5 个像素,然后转到下一张图片。 -
谢谢你,Mark,我是 python 新手,现在我明白我没有使用有效的方法。你的 cmets 很有帮助。我按照建议更改了代码。
-
至于 3d 推荐,是否意味着将两个循环结合起来?我没能成功。
-
你仍在为这一行的所有图像制作大量列表
img_gray.append(img_resize) -
谢谢你,马克
标签: numpy opencv image-processing python-imaging-library imutils