[英]How to reshape an ndarray to fir prediction model?
I need to read two images, convert them to size 150x150 and add them to an array that needs to be reshaped into a shape of (2, 150, 150, 3) in order to fit a keras model.我需要读取两个图像,将它们转换为 150x150 的大小并将它们添加到需要重新整形为 (2, 150, 150, 3) 形状的数组中,以适应 keras model。 Im having trouble understanding how numpy's reshape method works and how do i need to make use of it.我无法理解 numpy 的重塑方法是如何工作的,以及我需要如何使用它。
My code:我的代码:
import cv2
import numpy
def loadAndReshape(target, path):
targetImage = cv2.imread(path)
targetImage = cv2.cvtColor(targetImage, cv2.COLOR_BGR2RGB)
targetImage = cv2.resize(targetImage, dsize=(150, 150)) / 255
targetImage = targetImage.reshape(1, 150, 150, 3).astype('float32')
numpy.append(target, targetImage)
targetImages = numpy.ndarray((2, 150, 150, 3))
loadAndReshape(targetImages, './/test1.jpg')
loadAndReshape(targetImages, './/test2.jpg')
Reshaping targetImage
works without issues but in the end targetImages
will still be an empty ndarray.重塑targetImage
没有问题,但最终targetImages
仍然是一个空的 ndarray。 How do i go about outputting the array needed for my model?我如何 go 关于输出我的 model 所需的数组?
The function 'numpy.append' does not work inplace as I think you expect it to. function 'numpy.append' 不能像我想的那样就地工作。 Instead, you can do smth like:相反,您可以这样做:
mport cv2
import numpy as np
def loadAndReshape(image_list, path):
targetImage = cv2.imread(path)
targetImage = cv2.cvtColor(targetImage, cv2.COLOR_BGR2RGB)
targetImage = cv2.resize(targetImage, dsize=(150, 150)) / 255
targetImage = targetImage.reshape(1, 150, 150, 3).astype('float32')
image_list.append(targetImage)
targetImages = []
loadAndReshape(targetImages, './/test1.jpg')
loadAndReshape(targetImages, './/test2.jpg')
.
.
.
targetImages = np.concatenate(targetImages)
numpy.append return a copy, see https://numpy.org/doc/stable/reference/generated/numpy.append.html numpy.append return a copy, see https://numpy.org/doc/stable/reference/generated/numpy.append.html
You can try this:你可以试试这个:
import cv2
import numpy
def loadAndReshape(path):
targetImage = cv2.imread(path)
targetImage = cv2.cvtColor(targetImage, cv2.COLOR_BGR2RGB)
targetImage = cv2.resize(targetImage, dsize=(150, 150)) / 255
targetImage = targetImage.reshape(1, 150, 150, 3).astype('float32')
return targetImage
li = []
li.append(loadAndReshape('.//test1.jpg'))
li.append(loadAndReshape('.//test2.jpg'))
targetImages = np.array(li)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.