[PYTHON] [OpenCV] When you want to check if it is read properly with imread

I used OpenCV when converting images to npy format with TensorFlow, but I got stuck with an error, so I made a note.

Stupidly, I forgot that file I / O related functions would get stuck completely if I didn't handle exceptions when they failed. The imread function is one of them.

Below is a function that creates a dataset for tensorflow. The processing after reading the imread function is done with the None judgment. If you don't do this, you'll get moss on None, so you'll have to do this. (If you think about it, it's natural ...)

import os, sys
import numpy as np
import tensorflow as tf
import cv2

# config
flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_string('imgdir', '/home/hoge/fuga/piyo', 'Image dataset path')
flags.DEFINE_string('imgclasses', 4, 'The num of image dataset classes')
IMAGE_SIZE = 84 # the size of image
TRAIN_IMG_DIRS = os.listdir(FLAGS.imgdir)

def main():
  train_image, train_label = cvGetImageAndLabel()
  #The code for learning is troublesome, so it's omitted.

def cvGetImageAndLabel():
  images = []
  labels = []
  for i, d in enumerate(TRAIN_IMG_DIRS):
    files = os.listdir(FLAGS.imgdir + '/' + d)
    for f in files:
      img = cv2.imread(FLAGS.imgdir + '/' + d + '/' + f)
      #None judgment in this part
      if not img is None:
        img = cv2.resize(img, (IMAGE_SIZE, IMAGE_SIZE), interpolation = cv2.INTER_AREA)
        img = img.flatten().astype(np.float32)/255.0
        images.append(img)
        tmp = np.zeros(FLAGS.imgclasses)
        tmp[i] = 1
        labels.append(tmp)

  return np.asarray(images, dtype=np.float32), np.asarray(labels, dtype=np.float32)

if __name__ == '__main__':
  main()

I love the dirty code (?)

Reference link

http://stackoverflow.com/questions/23628325/cv2-imread-checking-if-image-is-being-read

Recommended Posts

[OpenCV] When you want to check if it is read properly with imread
When you want to use it as it is when using it with lambda memo
Don't write Python if you want to speed it up with Python
When it is troublesome to copy what you built with vue
[TensorFlow] If you want to run TensorBoard, install it with pip
AssertNumQueries is useful if you want to easily test N + 1 queries with django
If you want to enter the virtual environment with jupyter, nb_conda_kernels is recommended
Settings when you want to run python-mecab with travis
When you want to filter with Django REST framework
If you don't know how to draw the graph you want with matplotlib, it is convenient to look at the gallery.
When the variable you want to superscript with matplotlib is two or more characters
Solution when you want to use cv_bridge with python3 (virtualenv)
[AWS] What to do when you want to pip with Lambda
Use aggdraw when you want to draw beautifully with pillow
When you want to register Django's initial data with relationships
A site to see when you want to read a machine learning paper but it seems difficult
If you want to use field names with hyphens when updating firestore data in python
When you want to print to standard output with print while testing with pytest
When you want to send an object with requests using flask
I want to check the position of my face with OpenCV!
When you want to adjust the axis scale interval with APLpy
I want to detect objects with OpenCV
Gist repository to use when you want to try a little with ansible
If you want to include awsebcli with CircleCI, specify the python version
18 beautiful Python terms you want to read aloud. R18 with example sentences
If you want to get multiple statistics with groupby in pandas v1
Memorandum of means when you want to make machine learning with 50 images
Read CSV file with Python and convert it to DataFrame as it is
It is convenient to use stac_info and exc_info when you want to display traceback in log output by logging.
Workaround if you get an error when trying to install PySide with pip
It is more convenient to use csv-table when writing a table with python-sphinx
Personal best practice template to use when you want to make MVP with Flask
I want to write an element to a file with numpy and check it.
What to do if you get an error when installing python with pyenv
What to do if abort is displayed when inputting camera video in OpenCV
If you want to make a discord bot with python, let's use a framework
If you try to install Python2 pip after installing Python3 pip and it is rejected
Materials to read when getting started with Python
What to do if you get an OpenSSL error when installing Python 2 with pyenv
What to do if you get an Import Error when importing matplotlib with Jupyter
[Introduction to Python] What is the important "if __name__ =='__main__':" when dealing with modules?
What to do if you don't want to use Japanese column names when using ortoolpy.logistics_network
If you want to use Cython, also include python-dev
Check if it is Unix in the scripting language
Links to do what you want with Sublime Text
When you want to play a game via Proxy
Materials to read when getting started with Apache Beam
Things to do when you start developing with Django
When you want to plt.save in a for statement
Check if it is Unix in the scripting language
When it is troublesome to set up an SMTP server locally when sending mail with Python.
I know? Data analysis using Python or things you want to use when you want with numpy
Useful operation when you want to solve all problems in multiple programming languages with Codewars
If you want to put an argument in the closure function and execute it later
What to do if you get an Undefined error when trying to use pip with pyenv
If you try to make a word cloud with comments from WEB manga, it is interesting to visually understand what kind of manga it is.
One liner to hit if you forget where today is
[Django] A memorandum when you want to communicate asynchronously [Python3]
I want to initialize if the value is empty (python)
After all it is wrong to cat with python subprocess.
[Python] If you suddenly want to create an inquiry form