Opening an Image from a specific file? - python

import glob
import numpy as np
from PIL import Image
filename = glob.glob('/home/ns3/PycharmProjects/untitled1/stego.pgm')
im= Image.open(filename)
(x,y) = im.size
I = np.array(im.getdata()).reshape(y, x)
Keeps giving me this error:
im= Image.open(filename)
File "/home/ns3/.local/lib/python2.7/site-packages/PIL/Image.py", line 2416, in open
fp = io.BytesIO(fp.read())
AttributeError: 'list' object has no attribute 'read
How can I open an image from that specific path and use the image as array I?

The issue is that glob.glob() returns a list (a possibly-empty list of path names that match pathname) and you want a string.
so either insert a [0]
import glob
import numpy as np
from PIL import Image
filenames = glob.glob('/home/ns3/PycharmProjects/untitled1/stego.pgm')
filename = filenames[0]
im= Image.open(filename)
(x,y) = im.size
I = np.array(im.getdata()).reshape(y, x)
or skip glob all together
import numpy as np
from PIL import Image
filename = '/home/ns3/PycharmProjects/untitled1/stego.pgm'
im= Image.open(filename)
(x,y) = im.size
I = np.array(im.getdata()).reshape(y, x)

Related

How to solve this error: AttributeError: 'numpy.ndarray' object has no attribute 'crop'

I want to crop images with different sizes to get the same size to futher process them. I wrote the following code:
import glob
import cv2
import os
from matplotlib import pyplot as plt
inputFolder = "C:\\Users\\die5k\\Desktop\\hist\\Cropping\\input"
storeDirectory = "C:\\Users\\die5k\\Desktop\\hist\\Cropping\\output"
path = glob.glob(inputFolder + "\\*.png")
cv_img = []
image_no = 1
for img in path:
n = cv2.imread(img)
cv_img.append(n)
print(img)
os.chdir(storeDirectory)
cropped_img = n.crop(((w-100)//2, (h-100)//2, (w+100)//2, (h+100)//2))
filename = "Figure_" + str(image_no) + ".png"
plt.gcf().savefig(filename)
print(image_no)
image_no += 1
This outputs me the following error: AttributeError: 'numpy.ndarray' object has no attribute 'crop'
I am coding beginner and I dont know what I have to do.
It's because numpy doesn't have crop functionality. Try opening the image using PIL library and use the crop function as follows:
from PIL import Image
n = Image.open(path)
And then proceed with the crop.
Or Alternatively, you can crop it yourself without the function as follows:
cropped_img = n[((h-100)//2):((h-100)//2)+((h+100)//2), ((w-100)//2):((w-100)//2)+((w+100)//2)]

I faced some problems to enhance on multiple images using Python, It shows some error

Here, I want to change the default sharpness of the image dataset. It works fine for a single image, but when I apply on multiple images, it shows me an error like AttributeError: 'numpy.ndarray' object has no attribute 'filter'. What should I do to fix this? To that end, my code is given below-
from PIL import Image
from PIL import ImageEnhance
import cv2
import glob
dataset = glob.glob('input/*.png')
other_dir = 'output/'
for img_id, img_path in enumerate(dataset):
img = cv2.imread(img_path,0)
enhancer = ImageEnhance.Sharpness(img)
enhanced_im = enhancer.enhance(8.0)
cl2 = cv2.resize(enhanced_im, (1024,1024), interpolation = cv2.INTER_CUBIC)
cv2.imwrite(f'{other_dir}/enhanced_{img_id}.png',cl2)
You're trying to use PIL to enhance a numpy array. cv2 converts images from image paths into numpy arrays. This doesn't work with PIL image operations.
You can load the image using PIL, do the PIL enhancements then convert it to a numpy array to pass into your cv2.resize() method.
Try:
from PIL import Image
from PIL import ImageEnhance
import cv2
import glob
import numpy as np
dataset = glob.glob('input/*.png')
other_dir = 'output/'
for img_id, img_path in enumerate(dataset):
img = Image.open(img_path) # this is a PIL image
enhancer = ImageEnhance.Sharpness(img) # PIL wants its own image format here
enhanced_im = enhancer.enhance(8.0) # and here
enhanced_cv_im = np.array(enhanced_im) # cv2 wants a numpy array
cl2 = cv2.resize(enhanced_cv_im, (1024,1024), interpolation = cv2.INTER_CUBIC)
cv2.imwrite(f'{other_dir}/enhanced_{img_id}.png',cl2)

Adding a border to the image of dimension 250*250 to make 400*400

import cv2
import numpy as np
from PIL import Image
import glob
image_list =[]
resized_images=[]
for filename in
glob.glob('/home/ayush/Downloads/data/cars_test_resized/250*250/*.jpg'):
print(filename)
img = Image.open(filename)
image_list.append(img)
BLUE = [0,0,0]
for image in image_list:
constant=cv2.copyMakeBorder(np.float32(image),75,75,75,75,cv2.BORDER_CONSTANT,value=BLUE)
resized_images.append(constant)
print(constant.shape)
for (i,new) in enumerate(resized_images):
new.save('{}{}
{}'.format('/home/ayush/Downloads/data2/car_test/250*250',i+1,'.jpg'))
AttributeError
ipython-input-27-e2b9d48c48db> in <module>
1 for (i,new) in enumerate(resized_images):
----> 2 new.save('{}{}{}'.format('/home/ayush/Downloads/data2/car_test/250*250',i+1,'.jpg'))
AttributeError: 'numpy.ndarray' object has no attribute 'save'
Your error is trying to use a save method on the NumPy array.
You should instead use np.save(), so your line with the error is replaced by:
# Create file path
filepath = "{}{}{}".format('/home/ayush/Downloads/data2/car_test/250*250',i+1,'.jpg'))
# Save the numpy array
np.save(filepath, new)

How to convert multiple RGB images in one folder to grayscale in python

Someone could help me please, I want to convert my RGB images in one folder to grayscale at one time. I've been looking for some Python codes but haven't found any. I tried to do as following but it didn't work.
Here is my code:
from skimage.color import rgb2gray
from skimage.io import imread, imsave
from skimage.filters import threshold_otsu
from skimage import img_as_uint
inp_image = imread("C:/RGB/*.JPG")
img_gray = rgb2gray(inp_image)
thresh = threshold_otsu(img_gray)
binary_thresh_img = img_gray & gt; thresh
imsave("C:/Grayscale", img_as_uint(binary_thresh_img))
And it gave me following error:
OSError: [Errno 22] Invalid argument: 'C:/RGB/*.JPG'
You can get the list with the filenames with glob().
import glob
for filename in glob.glob("C:/RGB/*.JPG"):
inp_image = imread(filename)
[...]
To add to the list of solutions:
import os
from PIL import Image
ORIGIN_PATH = "./folder1/"
DESTIN_PATH = "./folder2/"
for filename in os.listdir(ORIGIN_PATH):
img = Image.open(ORIGIN_PATH + filename).convert("LA")
img.save(DESTIN_PATH + filename)

Python Image.open() does not recognize regular expression

from PIL import Image
image1 = "Image_I0000_F1_Filter 1_1A_health_2014-05-20_11.05.33.483.tiff"
image2 = "*F1*.tiff"
im1 = Image.open(image1)
im2 = Image.open(image2)
Tried to open the same image. im1 opens with no problem, but im2 shows IOError: [Errno 2] No such file or directory: '*F1*.tiff'.
Also tried
image2 = r"*F1*.tiff"
im2 = Image.open(image2)
and
image2 = "*F1*.tiff"
im2 = Image.open(open(image2,'rb'))
neither works.
PIL.Image.open has no glob matching. The documentation advises
You can use either a string (representing the filename) or a file object as the file argument
Notably not including glob matching.
Python uses the glob module to do glob matching.
from PIL import Image
import glob
filenames = glob.glob("*F1*.tiff")
# gives a list of matches, in this case most likely
# # ["Image_I0000_F1_Filter 1_1A_health_2014-05-20_11.05.33.483.tiff"]
if filenames:
filename = filenames[0]
else:
# what do we do if there's no such file? I guess pass the empty string
# to Image and let it deal with it
filename = ""
# or maybe directly...
raise FileNotFoundError
im1 = Image.open(filename)

Categories

Resources