Python 使用 Cat 和 Dog 数据的图像大小调整问题

Image resizing problem with Python using Cat and Dog data

我是数据可视化、机器学习和深度学习主题的新手。我正在努力提高自己,但是在尝试实现可视化时卡住了一个话题。

具体来说,我尝试在'Kaggle'上实现一个内核,我的数据是猫狗图像。我有训练和测试数据。问题是我的火车数据有太多不同大小、像素和形状的图片。我想把它们都做成1个形状。(例如,我想把所有的图片都做成64x64像素,或者128x128等)

""" I tried different codes to adjust its shapes and create plot:
I tried to reach 2 goals:
1. Convert the dog and cat images from RGB to Grayscale
2. Make all of the images 128x128, or 64x64 """


# One of the codes I've tried
img_size = 128
basewidth = 128
for image in tqdm(os.listdir(train_cat)): 
    path = os.path.join(train_cat, image)
    img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
    try:
       wpercent = (basewidth / float(img.size[0]))
       hsize = int((float(img.size[1]) * float(wpercent)))
       img = img.resize((basewidth, hsize), PIL.Image.ANTIALIAS)
    except:
        pass
    np_img=np.asarray(img)

for image2 in tqdm(os.listdir(train_dog)): 
    path = os.path.join(train_dog, image2)
    img2 = cv2.imread(path, cv2.IMREAD_GRAYSCALE) 
    try:
        wpercent = (basewidth / float(img2.size[0]))
        hsize = int((float(img2.size[1]) * float(wpercent)))
        img2 = img2.resize((basewidth, hsize), PIL.Image.ANTIALIAS)

    except:
        pass
    np_img2=np.asarray(img2) 

plt.figure(figsize=(10,10))
plt.subplot(1, 2, 1)
plt.imshow(np_img.reshape(img_size, img_size))
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(np_img2.reshape(img_size, img_size))
plt.axis('off')


# ---------------------------------------------------------------------
# Another way:

image_size = 128
for image in tqdm(os.listdir(train_dog)): 
    path = os.path.join(train_dog, image)
    img = cv2.imread(path, cv2.IMREAD_GRAYSCALE) 
    img = cv2.resize(img, (image_size, image_size)).flatten()   
    np_img=np.asarray(img)

for image2 in tqdm(os.listdir(train_cat)): 
    path = os.path.join(train_cat, image2)
    img2 = cv2.imread(path, cv2.IMREAD_GRAYSCALE) 
    img2 = cv2.resize(img2, (image_size, image_size)).flatten() 
    np_img2=np.asarray(img2)

plt.figure(figsize=(10,10))
plt.subplot(1, 2, 1)
plt.imshow(np_img.reshape(image_size, image_size))
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(np_img2.reshape(image_size, image_size))
plt.axis('off')
plt.title("Cat and Dogs in GrayScale")

第一个输出

ValueError         Traceback (most recent call last)
<ipython-input-47-0984b7467972> in <module>
     28 plt.figure(figsize=(10,10))
     29 plt.subplot(1, 2, 1)
---> 30 plt.imshow(np_img.reshape(img_size, img_size))
     31 plt.axis('off')
     32 plt.subplot(1, 2, 2)


ValueError: cannot reshape array of size 76964 into shape (300,300)

第二个输出

error    Traceback (most recent call last)
<ipython-input-67-99d190c6fd41> in <module>
      4     path = os.path.join(train_dog, image)
      5     img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
----> 6     img = cv2.resize(img, (image_size, image_size)).flatten()
      7     np_img=np.asarray(img)
      8 

error: OpenCV(4.1.0) /io/opencv/modules/imgproc/src/resize.cpp:3718:     error: (-215:Assertion failed) !ssize.empty() in function 'resize'

正如我上面提到的,我尝试将RGB 转换为灰度,并将图像的大小设为1 类型(128x128 可选)。我相信转换没有错误,但调整大小是一个我无法解决 2-3 天的问题,尽管我进行了大量研究。我不确定,但这可能是一个简单的问题,就像我说的,我现在是初学者。

注意:我添加了2种代码方式,因为有我最理解的代码。我希望,你能帮助我,或者教我一个新的方法,提前谢谢你:)

#Appendixes:

Cat and Dog Dataset: https://www.kaggle.com/tongpython/cat-and-dog

我尝试实现的调整大小和灰度代码取自: (在[5])

Base kaggle I'm saw in order to data that has images (In2)

您可以使用 skimage 进行图像大小调整和 gray/rgb 转换。

图片大小调整

skimage.transform.resize 文档

from skimage.transform import resize
# resize your grayscale image to 128x128
resized_image = resize(gray_image, (128,128))

灰度转换

skimage.color.rgb2gray 文档

from skimage.color import rgb2gray
gray_image = rgb2gray(color_image)

附加信息

  1. Skimage - 调整大小功能的奇怪结果
  2. scipy.misc.imresize

在执行图像处理时应避免混合使用 OpenCV 和 PIL。原因之一是因为 OpenCV 使用 BGR 格式,而 PIL 使用 RGB 格式。选择一个图书馆并坚持下去。要使用 OpenCV 将图像转换为灰度,您可以使用 cv2.cvtColor()cv2.COLOR_BGR2GRAYcv2.COLOR_RGB2GRAY 标志

image = cv2.imread('image.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

或者读入图片时传入一个flag

image = cv2.imread('image.png', 0) # OR
# image = cv2.imread('image.png', cv2.IMREAD_GRAYSCALE)

要调整大小,您只需使用 cv2.resize()

resized = cv2.resize(image, (64, 64)) # OR
# resized = cv2.resize(image, (128, 128)) 

注意,cv2.resize() 不保持纵横比。如果要保持纵横比,请查看imutils.resize()。虽然您可能无法获得确切的形状尺寸

resized = imutils.resize(image, width=64) # OR
# resized = imutils.resize(image, width=128)