Jay
Jay

Reputation: 410

it is easy to convert a jpg to a bmp on MacOS with OpenCV. is it possible to do the job with pillow?

it is very easy to convert a jpg to a bmp on MacOS with OpenCV.

import cv2
img = cv2.imread('a.jpg',1)
cv2.imwrite('a.bmp',img)

I am curious if it possible to do the job with pillow?

here is the piece of code on this post

from PIL import Image
import numpy as numpy

img = Image.open("xhty23.jpg").convert('L')

im = numpy.array(img)
fft_mag = numpy.abs(numpy.fft.fftshift(numpy.fft.fft2(im)))

visual = numpy.log(fft_mag)
visual = (visual - visual.min()) / (visual.max() - visual.min())

result = Image.fromarray((visual * 255).astype(numpy.uint8))
result.save('out.bmp')

the file saved by above looks like

enter image description here

which is far from a bmp format of original image.

saving image as bmp encounters error.

-------------------------------------------------------------------------- KeyError Traceback (most recent call last) in () 3 b = np.abs(np.fft.rfft2(a)) 4 j = Image.fromarray(b) ----> 5 j.save("a",".bmp")

~/anaconda3/envs/tf11/lib/python3.6/site-packages/PIL/Image.py in save(self, fp, format, **params) 1956 save_handler = SAVE_ALL[format.upper()] 1957 else: -> 1958 save_handler = SAVE[format.upper()] 1959 1960 if open_fp:

KeyError: '.BMP'

j.save("a.bmp")

gets this error

-------------------------------------------------------------------------- KeyError Traceback (most recent call last) ~/anaconda3/envs/tf11/lib/python3.6/site-packages/PIL/BmpImagePlugin.py in _save(im, fp, filename) 272 try: --> 273 rawmode, bits, colors = SAVE[im.mode] 274 except KeyError:

KeyError: 'F'

During handling of the above exception, another exception occurred:

OSError Traceback (most recent call last) in () 3 b = np.abs(np.fft.rfft2(a)) 4 j = Image.fromarray(b) ----> 5 j.save("a.bmp")

~/anaconda3/envs/tf11/lib/python3.6/site-packages/PIL/Image.py in save(self, fp, format, **params) 1967 1968 try: -> 1969 save_handler(self, fp, filename) 1970 finally: 1971 # do what we can to clean up

~/anaconda3/envs/tf11/lib/python3.6/site-packages/PIL/BmpImagePlugin.py in _save(im, fp, filename) 273 rawmode, bits, colors = SAVE[im.mode] 274 except KeyError: --> 275 raise IOError("cannot write mode %s as BMP" % im.mode) 276 277 info = im.encoderinfo

OSError: cannot write mode F as BMP

I already tried everything in this post, none of them works.

any ideas?

Upvotes: 1

Views: 1984

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207405

You can do that more simply with SIPS - Apple's built-in "Scriptable Image Processing System" which has shipped with all versions of macOS/OSX since the year dot. No need to install any Python or PIL/Pillow packages.

Just in Terminal:

sips -s format bmp input.jpg --out output.bmp

Upvotes: 1

Related Questions