Opening image from github with python PIL image.open() - python

I am hoping to classify some line drawings with a pretrained resnet model and am loading them from a github page. I think the error is coming from me setting up the location of the file wrong, but any help would be appreciated.
The link for the github is here
Here is my code:
loc = 'https://github.com/AlexSwiderski/Images/tree/main/pnt'
fname1 = 'ambulance_resized.png'
response = requests.get(loc + fname1)
image = Image.open(BytesIO(response.content)).resize((256, 256))
data = torch.from_numpy(np.asarray(image)[:, :, :3]) / 255.
My error is as follows:
UnidentifiedImageError Traceback (most recent call last)
<ipython-input-29-6e447d67525f> in <module>()
4 fname1 = 'ambulance_resized.png'
5 response = requests.get(loc + fname1)
----> 6 image = Image.open(BytesIO(response.content)).resize((256, 256))
7 data = torch.from_numpy(np.asarray(image)[:, :, :3]) / 255.
8
/usr/local/lib/python3.7/dist-packages/PIL/Image.py in open(fp, mode)
2894 warnings.warn(message)
2895 raise UnidentifiedImageError(
-> 2896 "cannot identify image file %r" % (filename if filename else fp)
2897 )
2898
UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7f61e16decb0>

You need add a slash before the string, otherwise the concatenated path would be
"https://github.com/AlexSwiderski/Images/tree/main/pntambulance_resized.png"
Which is invalid.
loc = 'https://github.com/AlexSwiderski/Images/tree/main/pnt'
fname1 = '/ambulance_resized.png'
response = requests.get(loc + fname1)
image = Image.open(BytesIO(response.content)).resize((256, 256))
data = torch.from_numpy(np.asarray(image)[:, :, :3]) / 255.

Related

Any idea why is this error? Could not find a format to read the specified file in mode 'i'

Im trying to read my dataset file through 'IMAGE_PATH' but it seems its not working. 'med/s' is my dataset file. Im using google colab as IDE.
IMAGE_PATH = 'meds/'
reader = easyocr.Reader(['en'], gpu=False)
result = reader.readtext(IMAGE_PATH)
result
```
i get this error
ValueError
Traceback (most recent call last)
<ipython-input-12-7400931fefc3> in <module>()
1 reader = easyocr.Reader(['en'], gpu=False)
----> 2 result = reader.readtext(IMAGE_PATH)
3 result
7 frames
/usr/local/lib/python3.7/dist-packages/imageio/core/functions.py in get_reader(uri, format, mode, **kwargs)
137 if format is None:
138 raise ValueError(
--> 139 "Could not find a format to read the specified file " "in mode %r" % mode
140 )
141
ValueError: Could not find a format to read the specified file in mode 'i'

Problem with loading image data using Pytorch dataset and dataloader

I have a problem with loading image data.
train_dir = 'images'
train_mask_dir = 'masks'
class TissueDataset(Dataset):
def __init__(self, image_dir, mask_dir, transforms=None):
self.image_dir = image_dir
self.mask_dir = mask_dir
self.transforms = transforms
self.images = os.listdir(image_dir)
def __len__(self):
return len(self.images)
def __getitem__(self, idx):
img_path = os.path.join(self.image_dir, self.images[idx])
mask_path = os.path.join(self.mask_dir, self.images[idx])
image = np.array(Image.open(img_path).convert('RGB'))
mask = np.array(Image.open(mask_path).convert('L'), dtype=np.float32)
mask = np.round(mask / 255).astype(np.float32)
if self.transforms:
aug = self.transforms(image=image, mask=mask)
image = aug['image']
mask = aug['mask']
return image, mask
train_dataset = TissueDataset(
image_dir = train_dir,
mask_dir = train_mask_dir,
transforms=None
)
train_loader = DataLoader(
train_dataset,
batch_size=BATCH_SIZE,
num_workers=2,
pin_memory=PIN_MEMORY,
shuffle=True
)
x, y = next(iter(train_loader))
print(f'x = shape: {x.shape}; type: {x.dtype}')
print(f'x = min: {x.min()}; max: {x.max()}')
print(f'y = shape: {y.shape}; class: {y.unique()}; type: {y.dtype}')
The error I have is following:
FileNotFoundError Traceback (most recent call last)
<ipython-input-36-869de9fa31b7> in <module>()
----> 1 x, y = next(iter(train_loader))
2
3 print(f'x = shape: {x.shape}; type: {x.dtype}')
4 print(f'x = min: {x.min()}; max: {x.max()}')
5 print(f'y = shape: {y.shape}; class: {y.unique()}; type: {y.dtype}')
3 frames
/usr/local/lib/python3.7/dist-packages/torch/_utils.py in reraise(self)
432 # instantiate since we don't know how to
433 raise RuntimeError(msg) from None
--> 434 raise exception
435
436
FileNotFoundError: Caught FileNotFoundError in DataLoader worker process 0.
Original Traceback (most recent call last):
File "/usr/local/lib/python3.7/dist-packages/torch/utils/data/_utils/worker.py", line 287, in _worker_loop
data = fetcher.fetch(index)
File "/usr/local/lib/python3.7/dist-packages/torch/utils/data/_utils/fetch.py", line 49, in fetch
data = [self.dataset[idx] for idx in possibly_batched_index]
File "/usr/local/lib/python3.7/dist-packages/torch/utils/data/_utils/fetch.py", line 49, in <listcomp>
data = [self.dataset[idx] for idx in possibly_batched_index]
File "<ipython-input-29-c33cd66a240c>", line 16, in __getitem__
mask = np.array(Image.open(mask_path).convert('L'), dtype=np.float32)
File "/usr/local/lib/python3.7/dist-packages/PIL/Image.py", line 2843, in open
fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'masks/2018_74969_1-1_2019-02-2100_48_39-lv1-35186-14908-3285-3747.jpg'
I cannot understand why it is showing right directory for wrong files (or otherwise) when images and masks are in the right directories. I've also checked my custom dataset and seems that it is working right (I can open this images).
img_path = os.path.join(train_dir, os.listdir(train_dir)[0])
mask_path = os.path.join(train_mask_dir, os.listdir(train_mask_dir)[3])
image = np.array(Image.open(img_path).convert('RGB'))
mask = np.array(Image.open(mask_path).convert('L'), dtype=np.float32)
mask = np.round(mask / 255).astype(np.float32)
print(mask_path)
print(img_path)
Output:
masks/18-09530A_2019-05-0723_50_03-lv1-34626-18358-3736-6181_mask.jpg
images/18-09530A_2019-05-0723_50_03-lv1-34626-18358-3736-6181.jpg
I will really appreciate any help or tip on this issue.
You can use exact paths like "C:\sample_folder\masks\example.jpg" in order to use relative paths like "masks/example.jpg".
Please check the values of these assignments
img_path = os.path.join(train_dir, os.listdir(train_dir)[0])
mask_path = os.path.join(train_mask_dir, os.listdir(train_mask_dir)[3])

storing a PILLOW image in same name after editing

I want to crop a set of Pillow images and save it with the same name in the same folder, from where it is opened. It is clustered and stored into 4 groups.
I wrote the code as below.
for c in range(4):
for image_file in glob.glob(f"plot_images/{c}/*.jpg"):
im=Image.open(image_file)
im = im.convert("RGB")
im = im.crop(offset)
im.save(im.filename)
It gives me the error
AttributeError Traceback (most recent call last)
<ipython-input-24-9f3d3a38e4e4> in <module>
15 im = im.crop(offset)
16 #im.show()
---> 17 im.save(im.filename)
18 #print(c,end='\r')
19
/srv/conda/envs/notebook/lib/python3.8/site-packages/PIL/Image.py in __getattr__(self, name)
539 )
540 return self._category
--> 541 raise AttributeError(name)
542
543 #property
AttributeError: filename
I don't understand why the error comes. please help.
If you check type(im) in different moments then you should see PIL.JpegImagePlugin.JpegImageFile after loading but PIL.Image.Image after converting which don't have filename. Use image_file instead of im.filename
im.save(image_file)
im = Image.open(image_file)
print(type(im)) # <class 'PIL.JpegImagePlugin.JpegImageFile'>
im = im.convert("RGB")
print(type(im)) # <class 'PIL.Image.Image'>
im = im.crop(offset)
print(type(im)) # <class 'PIL.Image.Image'>
im.save(image_file)

Image.open PermissionError: [Errno 13] Permission denied:

I am making an image classifier to classify rockets and airplanes using Python and TensorFlow, but I'm having trouble loading my training images folder with Pil.Image.Open. This is my code:
train_data = "C:/Users/Will Downs/image_training/training_data/"
test_data = "C:/Users/Will Downs/image_training/test_data/"
def train_data_with_label():
train_images = []
for i in tqdm(os.listdir(train_data)):
path = os.path.join(train_data, i)
img = Image.open(path)
img.thumbnail((64, 64), Image.ANTIALIAS) # resizes image in-place
train_images.append([np.array(img), one_hot_label(i)])
shuffle(train_images)
return train_images
def test_data_with_label():
test_images = []
for i in tqdm(os.listdir(test_data)):
path = os.path.join(test_data, i)
img = Image.open(path)
img.thumbnail((64, 64), Image.ANTIALIAS) # resizes image in-place
test_images.append([np.array(img), one_hot_label(i)])
shuffle(test_images)
return test_images
This is the error I get:
PermissionError Traceback (most recent call last)
<ipython-input-17-f3b44f76f884> in <module>
46 return test_images
47
---> 48 training_images = train_data_with_label()
49 testing_images = test_data_with_label()
50 tr_img_data = np.array([i[0] for i in training_images]).reshape(-1,64,64,1)
<ipython-input-17-f3b44f76f884> in train_data_with_label()
30 for i in tqdm(os.listdir(train_data)):
31 path = os.path.join(train_data, i)
---> 32 img = Image.open(path)
33 img.thumbnail((64, 64), Image.ANTIALIAS) # resizes image in-place
34 train_images.append([np.array(img), one_hot_label(i)])
~\Anaconda3\lib\site-packages\PIL\Image.py in open(fp, mode)
2768
2769 if filename:
-> 2770 fp = builtins.open(filename, "rb")
2771 exclusive_fp = True
2772
PermissionError: [Errno 13] Permission denied: 'C:/Users/Will Downs/image_training/training_data/Airplane'
Any suggestions on why this is or how I can fix it?
The issue was a simple folder formatting one. I had the images in folders based on their label, instead of being pooled together but named according to their label.

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
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?
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

Categories

Resources