I am writing a python program that applies filters to images. I am running an image through two different functions. One of them only takes .bmp files and the other doesn't take .bmp files but can take .gif or .ppm files. How do I convert the image from .bmp to .gif before running it through the second function.
You can use io module.
Something like this:
from io import BytesIO
with BytesIO()as image:
img.save(image, format='GIF') # the img is the picture you have already opened
image.seek(0) # move the pointer back to the beginning of the "file"
my_gif = Image.open(image)
Now you can work with my_gif object.
(Apr-25-2018, 05:26 AM)wavic Wrote: [ -> ]You can use io module.
Something like this:
from io import BytesIO
with BytesIO()as image:
img.save(image, format='GIF') # the img is the picture you have already opened
image.seek(0) # move the pointer back to the beginning of the "file"
my_gif = Image.open(image)
Now you can work with my_gif object.
Thank you! The solution you provided me works but I get an error when I try to implement it in my filter. Here is my code. Further below is the error. smoothImage is a function from mean_filter.py that improves the quality of pixelated images by applying a filter to them.
[inline]
import cv2
import io
from io import BytesIO
from mean_filter import *
myImage = cv2.imread("people3_pix.bmp")
cv2.imwrite("output.bmp", myImage)
with open("output.bmp", "r+") as img:
imageToFilter = img.read()
with BytesIO() as image:
imageToFilter.save(image, format = "GIF")
image.seek(0)
my_gif = Image.open(image)
myImage1 = smoothImage(my_gif)
[/inline]
[inline]Traceback (most recent call last):
File "test.py", line 10, in <module>
imageToFilter = img.read()
File "/usr/lib/python3.6/codecs.py", line 321, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x82 in position 2: invalid start byte
[/inline]
You are opening the image in 'r' mode. You should use 'b'
(Apr-25-2018, 07:48 PM)wavic Wrote: [ -> ]You are opening the image in 'r' mode. You should use 'b'
If I use "b" mode, I get:
[inline]Traceback (most recent call last):
File "test.py", line 11, in <module>
with open("output.bmp", "b+") as img:
ValueError: Must have exactly one of create/read/write/append mode and at most one plus
[/inline]
If I use "rb" mode, I get:
[inline]Traceback (most recent call last):
File "test.py", line 15, in <module>
imageToFilter.save(image, format = "GIF")
AttributeError: 'bytes' object has no attribute 'save'
[/inline]
Why 'b+'?
Why two ways to open an image? You already use the cv2 module for that. Why Python file IO?
imageToFilter = cv2.imread('output.bmp')