gpt4 book ai didi

python - 处理图像作为mnist模型的输入

转载 作者:行者123 更新时间:2023-12-02 16:23:02 25 4
gpt4 key购买 nike

我有一张需要检测其编号的图像。我为此开发了一个CNN模型。但是,因为我的图像具有不同的颜色格式(不同于在黑色背景上为白色的mnist输入),所以我需要对我的图像进行适当的处​​理。
input
这是输入图像。我需要将其转换为黑底白字,以便将其传递到模型中以检测3的数字。
我尝试从图像中删除边框,然后反转颜色以生成所需格式的图像。
到目前为止我的代码:

import cv2
import matplotlib.pyplot as plt

img_name = 'input.png'
image = cv2.imread(img_name, cv2.IMREAD_GRAYSCALE)
gray = cv2.resize(image, (256,256))
result = gray[40:216, 40:216]
因此,上面的代码在调整图像大小后会删除边框。这是我现在使用 cv2.imwrite()时获得的图像
result
然后我尝试将颜色反转如下:
ans = cv2.bitwise_not(result)
ans1 = (ans//145)*255 # so the only values present are 0 and 255
final result - ans1
这是我的最终形象。由于 3的键入非常粗,我的模型倾向于将其预测为8。有关如何以更好的方式处理图像的任何帮助将非常有帮助。非常感谢。
编辑1:
我想从图像中正确删除边框。在某些情况下,当我使用代码尝试图像时,图像也会被裁剪掉或边框仍然存在。
存在更多图片 here

最佳答案

一种方法是减去每个像素:(255 - gray)

import cv2

img = cv2.imread("gHeKR.png")
grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
inverted = 255 - grey
cv2.imwrite("inverted.png", cv2.resize(inverted, (256, 256)))
结果:
enter image description here
但是,仅通过 image-processing可能无法解决问题

But because my image is of a different color format (different from the mnist inputs which are white in black background), I need to process my image appropriately.


对于卷积层,图像颜色格式应该不是问题。
假设您对您的想法100%正确。然后使用 keras图像生成器填充图像。想法是从给定图像中填充更多样本,以便分类器学习正确的标签。
例如:
from keras.preprocessing.image import load_img, img_to_array
from keras.preprocessing.image import ImageDataGenerator

# Total Generated number
total_number = 5

data_gen = ImageDataGenerator(rescale=1. / 255, shear_range=0.2,
zoom_range=0.2, horizontal_flip=True)

# Create image to tensor
img = load_img("3/3.png", grayscale=True)
arr = img_to_array(img)
tensor_image = arr.reshape((1, ) + arr.shape)

for i, _ in enumerate(data_gen.flow(x=tensor_image,
batch_size=1,
save_to_dir="3",
save_prefix="generated",
save_format=".png")):
if i > total_number:
break
结果:
enter image description here enter image description here enter image description here enter image description here enter image description here
当然,您可以更改 datagen的参数,因为该想法是使用不同的参数对图像进行采样,因此CNN会正确标记3。
可能的问题1:为什么我不能百分百确定问题是颜色格式?

答:取决于您的CNN的准确性。如果您的MNIST的CNN准确度在99.2%到99.8%之间,那么使用 ImageGenerator可以解决您的问题。
但是,如果CNN的准确性低于99.2%,那么问题就出在您的体系结构中,首先您需要在MNIST上达到或超过99.2%的阈值准确性。更多信息请检查 website

关于python - 处理图像作为mnist模型的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63712084/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com