如何更改我的相机在 opencv 中读取的图像的大小?机器学习模型显示错误

How to change the size of image read by my camera in opencv? A machine learning model is showing error

我使用机器学习模型训练分类数据集,并使用 keras imagedatagenerator 进行增强。在程序中(实际上是分叉的)目标大小设置为(300,300),但在测试期间,当我使用我的电脑摄像头时,它显示以下错误:

ValueError:检查输入时出错:预期 conv2d_1_input 具有形状 (300, 300, 1) 但得到形状为 (260, 300, 1) 的数组

我不想再次将数据集训练到目标大小 (260,300),因为它导致了其他问题,那么 opencv 有没有办法解决这个问题,比如改变大小? opencv 程序用于视频捕获。

您可以使用 OpenCV 的调整大小功能:

resized_image = cv2.resize(image, (300, 300))

这会扭曲图像并可能导致模型性能不佳。

您的第二个选择是创建一个空的 numpy 数组(用 zeroes/ones 填充),大小为 300x300,并将图像放入该数组中。这样可以防止图像失真。

第二个选项:

output_img = np.ones((300, 300, 1)) * 128
output_img = (output_img).astype('uint8')

scale = 300 / (image.shape[0] * 1.0)
image_resize = cv2.resize(image, (0, 0), fx=scale, fy=scale, interpolation=cv2.INTER_LANCZOS4)

img_w = image_resize.shape[1]

if img_w < 300:
    #pad the image with values and make it 1:1 aspect ratio
    offset = img_w % 2
    output_img[:, int(300 / 2 - math.floor(img_w / 2)):int(300 / 2 + math.floor(img_w / 2) + offset), :] = image_resize

else:
    #crop the center of the image to maintain 1:1 aspect ratio
    output_img = image_resize[:,int(img_w / 2 - 300 / 2):
                  int(img_w / 2 + 300 / 2), :]