SoFunction
Updated on 2024-10-29

Python opencv and PIL image reading and saving and mutual conversion way

opencv and PIL image reading and saving and mutual conversion

1. opencv read display images

import cv2
img = ('')
('img', img)  # Picture display
()  # Input control in parenthesesimshowduration

Where waitKey() means wait for the user to press the key, if you don't add this sentence, the picture will show a flash.

cv2 reads the image i.e. img as, size i.e. (w,h,c).

2. PIL reads display pictures

from PIL import Image
image = ("")
()

No waitKey() is needed, the image will be displayed continuously.

image is in PIL format.

3. opencv and PIL interconversion

  • PIL to opencv
import cv2
from PIL import Image
import numpy
image = ("")  # PIL reading
img = ((image), cv2.COLOR_RGB2BGR)  # Conversion code
('img', img)  # opencv show
()

The PIL format is first converted to, and then converted to BGR for display via opencv, which uses the BGR format.

  • opencv to PIL
import cv2
from PIL import Image
img = ('')  # opencv read
image = ((img, cv2.COLOR_BGR2RGB))  # Conversion code
()  # PILdemonstrate

Convert numpy from BGR to RGB first, then to PIL format for display

4. Preservation of images

  • opencv save-imwrite()
import cv2
img = ('')
('', img)  # save as (a file)
  • PIL save-save()
from PIL import Image
image = ("")
('')  # save as (a file)

Interconversion of PIL images to OpenCV images

PILPictures withOpenCVThe interconversion of images is done through thearray formatConverted.

pass (a bill or inspection etc)type() function, we can observe that by()The format of the image obtained by the function is

pass (a bill or inspection etc)()The format of the image obtained by the function iswhile inImageMethods for loading images in array format exist in the

Therefore, using the array format as an intermediary can be realizedPILPictures withOpenCVThe interconversion of images between

The code is as follows:

import cv2
import numpy as np
from PIL import Image
def load_img_by_cv(file):
    return (file)
def load_img_by_PIL(file):
    return (file)
def cv2PIL(img_cv):
    return ((img_cv,cv2.COLOR_BGR2RGB))
def PIL2cv(img_pil):
    return ((img_pil),cv2.COLOR_RGB2BGR)

Note that bycv2 The default color channel format for loaded images isBGR This can be accomplished by function; the conversion is performed via thePIL The default color channel format for loaded images isRGB , which can be accessed through the image'sconvert method to perform the conversion.

summarize

The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.