如何解决将图像转换为 MNIST 格式
我已经训练了一个 KNN 模型来预测 MNIST 数据集中的手写图像。我现在想用我自己的笔迹测试它。我想将其转换为 MNIST 格式(图像中 784 像素的值作为数组)。我尝试将图像转换为 28*28 像素并将像素强度存储在下面的代码中:
img = cv2.imread(image,cv.IMREAD_GRAYSCALE)
resized = cv2.resize(img,(28,28))
features = resized.reshape(1,-1)
但由于某种原因它不起作用并且预测总是“0”。我想我需要将我自己的图像移动到 28x28 图像的中心并对其进行灰度化。我也认为我的图像没有正确转换为数组。有人能告诉我如何正确格式化我的图像以使预测更准确吗?
解决方法
我建议将您处理过的图像可视化以检查它是否居中并具有正确的对比度。请参阅:Visualize MNIST dataset using OpenCV or Matplotlib/Pyplot
,以下代码应该可以正常工作,或者您可能需要稍微调整一下。函数名称一目了然。
import numpy as np
import cv2
def resize_to_28x28(img):
img_h,img_w = img.shape
dim_size_max = max(img.shape)
if dim_size_max == img_w:
im_h = (26 * img_h) // img_w
if im_h <= 0 or img_w <= 0:
print("Invalid Image Dimention: ",im_h,img_w,img_h)
tmp_img = cv2.resize(img,(26,im_h),cv2.INTER_NEAREST)
else:
im_w = (26 * img_w) // img_h
if im_w <= 0 or img_h <= 0:
print("Invalid Image Dimention: ",im_w,(im_w,26),cv2.INTER_NEAREST)
out_img = np.zeros((28,28),dtype=np.ubyte)
nb_h,nb_w = out_img.shape
na_h,na_w = tmp_img.shape
y_min = (nb_w) // 2 - (na_w // 2)
y_max = y_min + na_w
x_min = (nb_h) // 2 - (na_h // 2)
x_max = x_min + na_h
out_img[x_min:x_max,y_min:y_max] = tmp_img
return out_img
def run_inference(img):
tsr_img = resize_to_28x28(img)
input_data = np.copy(tsr_img).reshape(1,28,1)
if floating_model:
input_data = (np.float32(input_data) - input_mean) / input_std
# Instantiate tensorflow interpreter and run inference on input_data
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。