【问题标题】:How to resize image regions for CNN?如何调整 CNN 的图像区域大小?
【发布时间】:2019-07-19 18:18:22
【问题描述】:

我正在使用 AlexNet 进行对象识别。我已经使用大小为 (277,277) 的图像训练了我的模型。然后使用选择性搜索算法从图像中提取区域并将这些区域馈送到网络进行测试/预测。 但是,当我调整图像区域的大小(来自 SelectiveSearch)时,它会给出错误。

调整训练图像大小的代码:

try:
 img_array = cv2.imread(os.path.join(path,img))
 new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
 gray_img = cv2.cvtColor(new_array, cv2.COLOR_BGR2GRAY)
 training_data.append([gray_img, class_num])

except Exception as e:
 pass

调整所选图像区域大小的代码:

img_lbl, regions = selectivesearch.selective_search(img, scale=500, sigma=0.4, min_size=10)
for r in regions:
 x, y, w, h = r['rect']
 segment = img[y:y + h, x:x + w]
 gray_img = cv2.resize(segment, (277, 277))
 gray_img = cv2.cvtColor(gray_img, cv2.COLOR_BGR2GRAY)
 gray_img = np.array(gray_img).reshape(-1, 277, 277, 1)
 gray_img = gray_img / 255.0
 prediction = model.predict(gray_img)

它在最后一行给出错误,即:

预测 = model.predict(gray_img)

错误是:

错误:检查输入时出错:预期 conv2d_1_input 的形状为 (227, 227, 1),但得到的数组的形状为 (277, 277, 1)

当两个形状相同时,为什么会出现此错误。

【问题讨论】:

  • 你能展示你用所有层和东西创建的神经网络吗?
  • 对不起,我忘记更新了。我已经解决了这个问题。我自己不知道是什么问题,但是当我重写代码时它工作正常。

标签: python tensorflow conv-neural-network


【解决方案1】:

您的模型需要一个张量作为输入,但您正在尝试对一个 numpy 数组进行评估。而是使用给定形状的占位符,然后在会话中将您的数组输入此占位符。

# define a placeholder for input 
image = tf.placeholder(dtype=tf.float32, name="image", shape=[277,277,1])
prediction = model.predict(image)

# evaluate each of your resized images in a session
with tf.Session() as sess:
    for r in regions:
        x, y, w, h = r['rect']
        # rest of your code from the loop here 
        gray_img = gray_img /255.
        p = sess.run(prediction, feed_dict={image: gray_img})
        print(p) # to print the prediction of your model for this image

也许你应该看看这个问题:What's the difference between tf.placeholder and tf.Variable?

【讨论】:

  • 我应该删除调整大小和重塑代码行并放置这些行吗?或者我应该在调整图像大小和重塑图像后放置这些行。
  • 现在它给了我这个错误:错误:无法将大小为 6900 的数组重新整形为形状 (277,277,1)
  • 您的代码不完整,所以我无法确切告诉您为什么会出现此错误。通常,您希望使用占位符定义模型作为输入,然后将值(调整大小的图像)映射到该占位符。
  • 当然@UmamaKhalid!如果您使用我发布的代码,请考虑支持我的回答。
猜你喜欢
  • 2011-11-26
  • 2019-05-27
  • 2014-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-23
相关资源
最近更新 更多