Skip to content

Instantly share code, notes, and snippets.

@Jongbhin
Created April 26, 2020 23:21
Show Gist options
  • Save Jongbhin/c23552c30d8f4a16f2a5adabd1dfbc47 to your computer and use it in GitHub Desktop.
Save Jongbhin/c23552c30d8f4a16f2a5adabd1dfbc47 to your computer and use it in GitHub Desktop.
[PIL open cv image open and convert to numpy array] #pil, #cv2, #numpy
# -*- coding:utf-8 -*-
import sys
import os
from tqdm import tqdm
import cv2
from collections import defaultdict
import numpy as np
from PIL import Image
jpg_file = "1559438627_L300.jpg"
png_file = "1559438627_L300.png"
cv2_img = cv2.imread(jpg_file)
cv2_array = np.asarray(cv2_img)
print(cv2_img.shape)
pil_img = Image.open(jpg_file)
pil_array = np.asarray(pil_img)
print("pil shape : {}".format(pil_array.shape))
print("cv2 shape : {}".format(cv2_array.shape))
# pil shape : (400, 400, 3)
# cv2 shape : (400, 400, 3)
grey_cv2 = np.asarray(cv2.imread(jpg_file, 0))
grey_pil = np.asarray(pil_img.convert('L'))
print("pil grey shape : {}".format(grey_pil.shape))
print("cv2 grey shape : {}".format(grey_cv2.shape))
# pil grey shape : (400, 400, 2)
# cv2 grey shape : (400, 400)
pil_to_grey_cv2 = cv2.cvtColor(pil_array
, cv2.COLOR_RGB2GRAY)
print("pil to cv2 grey shape : {}".format(pil_to_grey_cv2.shape))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment