OSError: cannot identify image file 'file_name' - python

I have already read answer of this question Image.open() cannot identify image file - Python?, that question was solved by using from PIL import Image, but my situation is different. I am using image_slicer, and there I am getting these errors:
Traceback (most recent call last):
File "image_slice.py", line 17, in <module>
j=image_slicer.slice('file_name' , n_k)
File "/home/user_name/.local/lib/python3.5/site-
packages/image_slicer/main.py", line 114, in slice
im = Image.open(filename)
File "/home/user_name/.local/lib/python3.5/site-packages/PIL/Image.py", line 2687, in open
% (filename if filename else fp))
OSError: cannot identify image file 'file_name'
The full code is:
import os
from PIL import Image
import image_slicer
import numpy as np
import nibabel as nib
img = nib.load('/home/user_name/volume-20.nii')
img.shape
epi_img_data = img.get_data()
#epi_img_data.shape
n_i, n_j, n_k = epi_img_data.shape
center_i = (n_i - 1) // 2
center_j = (n_j - 1) // 2
center_k = (n_k - 1) // 2
centers = [center_i, center_j, center_k]
print("Co-ordinates in the voxel array: ", centers)
#for i in range(n_k):
j=image_slicer.slice('/home/user_name/volume-20.nii' , n_k)
However nib.load(), works fine, but image_slicer is not working.
All the nii images are 3D images.

Image slicer is not intended for reading nii format. Here is the list of supported formats.

This error also occurs whenever the image file itself is corrupted. I once accidentally was in the process of deleting the subject image, until canceling mid-way through.
TL;DR - open image file to see if it's ok.

Related

How to get set of colours in an processed image using python PIL

I have an image and when I process it, I can´t get the colors.
Here is my code:
import cv2
from PIL import Image
im = Image.open ('imag.jpg')
ret,thresh1 = cv2.threshold(im,127,255,cv2.THRESH_BINARY)
from collections import defaultdict
by_color = defaultdict(int)
for pixel in thresh1.getdata():
by_color[pixel] += 1
print (by_color)
If I run just the original image (im), works well. But when I run processed image (thresh1), the following error appears:
Traceback (most recent call last):
File "file.py", line 62, in <module>
ret,thresh1 = cv2.threshold(im,127,255,cv2.THRESH_BINARY)
TypeError: Expected cv::UMat for argument 'src'
For this function:
ret,thresh1 = cv2.threshold(im,127,255,cv2.THRESH_BINARY)
to work you should read image using cv2.imread (returns numpy.array) rather than PIL.Image.open (returns Image object).

PIL open image from base64 failed

I'm trying to convert a base64 string to image and get the following error.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 2288, in open
% (filename if filename else fp))
IOError: cannot identify image file <cStringIO.StringI object at 0x7fe6d9e88828>
There is no prefix like data:image/png;base64. I get the base64 string from an image and try to convert it back to an image. Here is my code.
# -*- coding: utf-8 -*-
import requests
import base64
from PIL import Image
from cStringIO import StringIO
import zipfile
r = requests.get('https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png', stream=False)
img = Image.open(StringIO(r.content))
b64str = base64.b64encode(img.tobytes())
data = base64.b64decode(b64str)
newimg = Image.open(StringIO(data))
And I get the error above. Can anyone help? Thanks!
You open .PNG file from the web and get the RAW image, which is RGB values, then encode that into base64 and back, which still gives you RAW RGB values which cannot be read by Image.open() because these are not an image file (jpg, png, etc), but RAW RGB values.
The most reasonable would be:
newImg = data # that's it
Or if you want to make an Image:
newImg = Image.frombytes(img.mode, img.size, data)
and get mode and size from the original image.

"ValueError: cannot filter palette images" during Pytesseract Conversion

Having trouble with this error code regarding the following code for Pytesseract. (Python 3.6.1, Mac OSX)
import pytesseract
import requests
from PIL import Image
from PIL import ImageFilter
from io import StringIO, BytesIO
def process_image(url):
image = _get_image(url)
image.filter(ImageFilter.SHARPEN)
return pytesseract.image_to_string(image)
def _get_image(url):
r = requests.get(url)
s = BytesIO(r.content)
img = Image.open(s)
return img
process_image("https://www.prepressure.com/images/fonts_sample_ocra_medium.png")
Error:
/usr/local/Cellar/python3/3.6.0_1/Frameworks/Python.framework/Versions/3.6/bin/python3.6 /Users/g/pyfo/reddit/ocr.py
Traceback (most recent call last):
File "/Users/g/pyfo/reddit/ocr.py", line 20, in <module>
process_image("https://www.prepressure.com/images/fonts_sample_ocra_medium.png")
File "/Users/g/pyfo/reddit/ocr.py", line 10, in process_image
image.filter(ImageFilter.SHARPEN)
File "/usr/local/lib/python3.6/site-packages/PIL/Image.py", line 1094, in filter
return self._new(filter.filter(self.im))
File "/usr/local/lib/python3.6/site-packages/PIL/ImageFilter.py", line 53, in filter
raise ValueError("cannot filter palette images")
ValueError: cannot filter palette images
Process finished with exit code 1
Seems simple enough, but is not working. Any help would be greatly appreciated.
The image you have is a pallet-based image. You need to convert it to a full RGB image in order to use the PIL filters.
import pytesseract
import requests
from PIL import Image, ImageFilter
from io import StringIO, BytesIO
def process_image(url):
image = _get_image(url)
image = image.convert('RGB')
image = image.filter(ImageFilter.SHARPEN)
return pytesseract.image_to_string(image)
def _get_image(url):
r = requests.get(url)
s = BytesIO(r.content)
img = Image.open(s)
return img
process_image("https://www.prepressure.com/images/fonts_sample_ocra_medium.png")
You should also note that the the .convert() and .filter() methods return a copy of the image, they don't change the existing image object. You need to assign the return value to a variable as shown in the code above.
NOTE: I don't have pytesseract, so I can't check the last line of process_image().

How to use Python to convert .r8 image files to .ppm?

I'm trying to convert .r8 files to ppm files using a python scrpit.
The scrpit works when converting .jpg files, but doesn't seem to work with .r8 files.
import PIL.Image
import os, os.path, string, sys
openfile = '/Users/.../.../Image_converter'
im = PIL.Image.open('Test0.r8')
im = im.convert('RGB')
im.save('Test0.ppm')
im.show('Test0.ppm')
Traceback (most recent call last):
File "R8_to_PPM.py", line 7, in <module>
im = PIL.Image.open('Test0.r8')
File "/Users/FirstDawn/anaconda/lib/python2.7/site-packages/PIL/Image.py", line 2286, in open
% (filename if filename else fp))
IOError: cannot identify image file 'Test0.r8'
Is there anyway to make this conversion using python? (Or another language?)
I'm using python 2.7 on a MacOS. (.r8 = raw graphics (one byte per pixel) plane one (PicLab))
Thank you.

RuntimeError using cv.SaveImage in openCV

I want to convert a jpg file to png, but when I run this code :
from opencv import _cv
from opencv.highgui import cvSaveImage, cvLoadImage
cvSaveImage("bet.jpg",cvLoadImage("bet.jpg"))
if __name__ == '__main__':
pass
It gives this error which I don't understand :
Traceback (most recent call last):
File "convert.py", line 6, in <module>
cvSaveImage("bet.jpg",cvLoadImage("bet.jpg"))
File "/usr/lib/pymodules/python2.6/opencv/highgui.py", line 183, in cvSaveImage
return _highgui.cvSaveImage(*args)
RuntimeError: openCV Error:
Status=Null pointer
function name=cvGetMat
error message=NULL array pointer is passed
file_name=cxarray.cpp
line=2780
I have my picture with the same folder of source code and the name of the image is bet.jpg
Any idea ??
The best choice is pyopencv:
import pyopencv as cv
img = cv.imread('01.png')
cv.imshow('img-windows',img)
cv.waitKey(0)
cv.imwrite('01.png',img)
From Python CV documentation, the CV2 method for converting a jpeg to png is:
Python: cv2.imwrite(filename, img[, params]) → retval
For my example:
import cv2
filename = 'pic.jpeg'
cam = cv2.VideoCapture(filename)
s, img = cam.read()
picName = 'pic.png'
cv2.imwrite(picName, img)
VideoCapture is nice and general, and works with videos, webcams and image files.
I solved the problem, the image I took randomly from the Google Images doesn't load. Maybe it's encrypted or something I don't know. I tried it with other images, and worked very well. So watch out while copying images : )

Categories

Resources