Skip to content

Instantly share code, notes, and snippets.

@JoshVarty
Created October 27, 2019 23:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshVarty/5ada5505ae49bc470faa3dd21d7dcc94 to your computer and use it in GitHub Desktop.
Save JoshVarty/5ada5505ae49bc470faa3dd21d7dcc94 to your computer and use it in GitHub Desktop.
Testing out a few different ways of loading images.
def get_img_pil(path):
img = Image.open(path)
arr = np.asarray(img)
img.close()
del img
return arr
def get_img_cv2(path):
img = cv2.imread(path)
return cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
def get_img_cv2_no_leak(path):
#read the data from the file
with open(path, 'rb') as infile:
buf = infile.read()
#use numpy to construct an array from the bytes
x = np.frombuffer(buf, dtype='uint8')
#decode the array into an image
img = cv2.imdecode(x, cv2.IMREAD_UNCHANGED)
del x
del buf
return img
def get_img_pil_no_leak(path):
with open(path, 'rb') as f:
img = Image.open(f)
# We need to consume the whole file inside the `with` statement
img.load()
arr = np.asarray(img)
# Unref here to be sure that there is nothing happens
# with the image after file is closed
img = None
return arr
def load_samples(img_ids):
samples = []
for img_id in img_ids:
path = "data/train_images/" + img_id
img = get_img_cv2(path)
# img = get_img('data/test_images/fff3c5c.jpg')
samples.append(img)
return samples
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment