0

Python 3.6.3

How do i do the following without saving and loading the picture over and over again, is there a way to convert the image between the two formats? (Allowing me to only load the picture once at the beginning and save once at the end.)

from PIL import Image
import cv2
import numpy as np

img = Image.open(r'C:\Users\Chris\Desktop\programs\pic.jpg')
#modify picture using PIL functions
img.save(r'C:\Users\Chris\Desktop\programs\pic.jpg')

img = cv2.imread("pic.jpg")
#modify picture using cv2 functions
cv2.imwrite("pic.jpg", img)

img = Image.open(r'C:\Users\Chris\Desktop\programs\pic.jpg')
#modify picture using PIL functions
img.save(r'C:\Users\Chris\Desktop\programs\pic.jpg)')
Jeru Luke
  • 20,118
  • 13
  • 80
  • 87
Chrisp
  • 45
  • 1
  • 7
  • 1
    I don't use cv2, but doesn't `cv2.imread` just return a Numpy array? You can convert a Numpy array to a PIL image using `Image.fromarray` and you can convert a PIL image to a Numpy array with `np.asarray(img)`. However, PIL use RGB order and cv2 uses BGR order, but that's easy enough to handle with Numpy operations. – PM 2Ring Dec 11 '17 at 05:44
  • 1
    The linked answer uses `cv2.cvtColor(img, cv2.COLOR_BGR2RGB)` to reverse the color channel order. To do it in Numpy you can do [`np.flip(img, axis=-1)`](https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.flip.html) which creates a new view of the `img` array, so it's very fast. – PM 2Ring Dec 11 '17 at 05:58
  • oh sorry i searched but didnt find that, should i delete this post since its a duplicate? thanks a tonne – Chrisp Dec 11 '17 at 09:05
  • There's no need to delete this question: it might help a future reader to find the linked question. – PM 2Ring Dec 11 '17 at 09:12

0 Answers0