使用OpenCV或Matplotlib/Pyp可视化MNIST数据集

2024-06-16 11:38:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有MNIST数据集,我正在尝试使用pyplot将其可视化。数据集采用cvs格式,其中每行是一幅784像素的图像。我想用28*28图像格式的pyplotopencv来可视化它。我试图直接使用:

plt.imshow(X[2:],cmap =plt.cm.gray_r, interpolation = "nearest") 

但我不工作?关于我该如何处理这个问题的任何想法。


Tags: 数据图像可视化格式图像格式cmplt像素
3条回答

对于所有像我这样想要一个快速而肮脏的解决方案的人来说,只需在控制台中,在没有花哨的库的情况下,大致了解一个给定的输入是关于什么的:

def print_greyscale(pixels, width=28, height=28):
    def get_single_greyscale(pixel):
        val = 232 + round(pixel * 23)
        return '\x1b[48;5;{}m \x1b[0m'.format(int(val))

    for l in range(height):
        line_pixels = pixels[l * width:(l+1) * width]
        print(''.join(get_single_greyscale(p) for p in line_pixels))

(期望输入的形状像[784],浮点值从0到1。如果两者都不是,则可以轻松转换(例如pixels = pixels.reshape((784,))pixels \= 255

Output

输出有点失真,但你明白了。

导入必要的包

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

将mnist train数据集(csv格式)读取为pandas数据帧

s = pd.read_csv("mnist_train.csv")

将pandas数据帧转换为numpy矩阵

data = np.matrix(s)

第一列包含标签,因此将其存储在单独的数组中

output = data[:, 0]

从数据矩阵中删除第一列

data = np.delete(data, 0, 1)

第一行表示第一个图像,它是28X28图像(存储为784像素)

img = data[0].reshape(28,28)

[And displaying the image][1]
plt.imshow(img, cmap="gray")

enter image description here

假设您有一个具有此格式的CSV文件,即MNIST数据集可用的格式

label, pixel_1_1, pixel_1_2, ...

下面是如何使用Matplotlib和OpenCV在Python中可视化它的方法

Matplotlib/Pyplot

import numpy as np
import csv
import matplotlib.pyplot as plt

with open('mnist_test_10.csv', 'r') as csv_file:
    for data in csv.reader(csv_file):
        # The first column is the label
        label = data[0]

        # The rest of columns are pixels
        pixels = data[1:]

        # Make those columns into a array of 8-bits pixels
        # This array will be of 1D with length 784
        # The pixel intensity values are integers from 0 to 255
        pixels = np.array(pixels, dtype='uint8')

        # Reshape the array into 28 x 28 array (2-dimensional array)
        pixels = pixels.reshape((28, 28))

        # Plot
        plt.title('Label is {label}'.format(label=label))
        plt.imshow(pixels, cmap='gray')
        plt.show()

        break # This stops the loop, I just want to see one

enter image description here

开放简历

可以从上面获取pixelsnumpy数组,该数组是dtype='uint8'(无符号8位整数)和形状28 x 28,并用cv2.imshow()绘制

    title = 'Label is {label}'.format(label=label)

    cv2.imshow(title, pixels)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

相关问题 更多 >