Im trying to make a function which needs as input an image file in jpg format and outputs an array every time i call it. This is what i achieved so far:
import scipy.misc as sm
import numpy as np
from PIL import Image
def imagefunc(image):
try:
i = Image.open(image)
if i.format == 'jpg':
return i.format == 'jpg'
except OSError: # Checking for different possible errors in the input file
print ('This is not a jpg image! Input has to be a jpg image!')
return False
except FileNotFoundError: # Another check for error in the input file
print ('No image was found! Input file has to be in the same directory as this code is!')
return False
imgarray = np.array(sm.imread(image, True))
return imgarray
The problem is that when i call it, "imagefunc(kvinna)" to open a jpeg picture it outputs: NameError: name 'kvinna' is not defined. What am i missing here? Is the code wrong or is it file directory problem? Thanks
Reading and Writing Images
You are not opening the image correctly, hence the Name Error
i = Image.open(image) # image should be "image_name.ext"
here image should be "kvinna.jpeg" with the extension.
so the function call will be: imagefunc("kvinna.jpeg") further check or either jpeg or jpg in your function definition.
Image.open(image) returns an Image object, later check the extension for it.
Related
I am trying to load the following file: 'data/chapter_1/capd_yard_signs\\Dueñas_2020.png'
But when I do so, cv2.imread returns an error: imread_('data/chapter_1/capd_yard_signs\Due├▒as_2020.png'): can't open/read file: check file path/integrity load file
When I specified the file name with os.path.join, I tried encoding and decoding the file
f = os.path.join("data/chapter_1/capd_yard_signs", filename.encode().decode())
But that didn't solve the problem.
What am I missing?
This is how I ended up getting it to work:
from PIL import Image
pil = Image.open(f).convert('RGB') # load the image with pillow and make sure it is in RGB
pilCv = np.array(pil) # convert the image to an array
img = pilCv[:,:,::-1].copy() # convert the array to be in BGR
I am trying norm my document data input and I am facing a lot of .pdf, .tiff, and .tiff documents.
I want to normalise all documents by getting them into .pdf format but facing issues with the .tif documents in my to pdf conversion function.
The problem is dealing with
def tiff_to_pdf(tiff_path: str) -> str:
if tiff_path.endswith(".tif"):
tiff_path.replace(".tif", ".tiff")
pdf_path = tiff_path.replace('.tiff', '.pdf')
if not os.path.exists(tiff_path): raise Exception(f'{tiff_path} does not find.')
image = Image.open(tiff_path)
images = []
for i, page in enumerate(ImageSequence.Iterator(image)):
page = page.convert("RGB")
images.append(page)
if len(images) == 1:
images[0].save(pdf_path)
else:
images[0].save(pdf_path, save_all=True, append_images=images[1:])
return pdf_path
Also simply trying to load the .tif as in the snippet below causes an error:
fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'a_image.tif'
from PIL import Image
im = Image.open('a_image.tif')
im.show()
I honestly checked the directory and it is finding every .tiff file and is able to get a pdf out of it, but not working with .tif files.
Any help would be highly appreciated and intermediate steps to get from .tif to .pdf are of course fine.
You change in string .tif to .tiff but you don't assign new string to variable.
But you should change .tif directly to .pdf
if tiff_path.endswith(".tif"):
pdf_path = tiff_path.replace(".tif", ".pdf")
elif tiff_path.endswith(".tiff"):
pdf_path = tiff_path.replace('.tiff', '.pdf')
else:
print('Wrong extension:', tiff_path)
return # exit function with `None` when extension is wrong
# or raise error
# raise Exception(f'{tiff_path} has wrong extension.')
# ... code which converts image to PDF ...
image = Image.open(tiff_path)
# ...
images[0].save(pdf_path)
# ...
images[0].save(pdf_path, save_all=True, , append_images=images[1:])
And when you check file then you may need to use full path
im = Image.open('/full/path/to/a_image.tif')
because code may run in different folder and it may not find this file in different folder.
Code:
import zxing
from PIL import Image
reader = zxing.BarCodeReader()
path = 'C:/Users/UI UX/Desktop/Uasa.png'
im = Image.open(path)
barcode = reader.decode(path)
print(barcode)
when i use code above work fine and return result:
BarCode(raw='P<E....
i need to use this code:
import zxing
import cv2
reader = zxing.BarCodeReader()
path = 'C:/Users/UI UX/Desktop/Uasa.png'
img = cv2.imread (path)
cv2.imshow('img', img)
cv2.waitKey(0)
barcode = reader.decode(img)
print(barcode)
but this code return an error:
TypeError: expected str, bytes or os.PathLike object, not numpy.ndarray
In another program i have image at base64 could help me somewhere here?
any body could help me with this?
ZXing does not support passing an image directly as it is using an external application to process the barcode image. If you're not locked into using the ZXing library for decoding PDF417 barcodes you can take a look at the PyPI package pdf417decoder.
If you're starting with a Numpy array like in your example then you have to convert it to a PIL image first.
import cv2
import pdf417decoder
from PIL import Image
npimg = cv2.imread (path)
cv2.imshow('img', npimg)
cv2.waitKey(0)
img = Image.fromarray(npimg)
decoder = PDF417Decoder(img)
if (decoder.decode() > 0):
print(decoder.barcode_data_index_to_string(0))
else:
print("Failed to decode barcode.")
You cannot. if you look at the source code you will see that what it does is call a java app with the provided path (Specifically com.google.zxing.client.j2se.CommandLineRunner).
If you need to pre-process your image then you will have to save it somewhere and pass the path to it to your library
I fix this by:
path = os.getcwd()
# print(path)
writeStatus = cv2.imwrite(os.path.join(path, 'test.jpg'), pdf_image)
if writeStatus is True:
print("image written")
else:
print("problem") # or raise exception, handle problem, etc.
sss = (os.path.join(path, 'test.jpg'))
# print(sss)
pp = sss.replace('\\', '/')
# print(pp)
reader = zxing.BarCodeReader()
barcode = reader.decode(pp)
The zxing package is not recommended. It is just a command line tool to invoke Java ZXing libraries.
You should use zxing-cpp, which is a Python module built with ZXing C++ code. Here is the sample code:
import cv2
import zxingcpp
img = cv2.imread('myimage.png')
results = zxingcpp.read_barcodes(img)
for result in results:
print("Found barcode:\n Text: '{}'\n Format: {}\n Position: {}"
.format(result.text, result.format, result.position))
if len(results) == 0:
print("Could not find any barcode.")
I am using OpenCV to try and process an image for my python class.
to load the image we are asked to retrieve a fully qualified path from the user and then also check if the path is valid. If the path is invalid I need to print a warning message and then terminate the function using return None. If the path is valid I want to print a success message and then return the value of the variable that I read the image into.
here is the code I have so far:
import cv2
import os
img_path = input("Enter a fully qualified path for an image: ")
#define a function to load an image
def img_loader():
try:
img = cv2.imread(img_path)
#exists = os.path.isfile(img_path) #I used this in my if/else statement
print("Success! The image path exists")
return ReturnValue(img)
except Exception:
print("WARNING: The file path you entered was incorrect.")
return None
when I run this script it gets the user input and then returns nothing at all (even when I commented out the 'return None' command)
I know that the path I'm using is correct but I'm not sure if I'm using the cv2.imread command correctly.
I've tried using both if/else and try/except for checking the path but I got the same result with both
How can I get my script to read the image into a variable and then return its value to the screen. Note: my teacher said that the value returned should be some sort of list
Thanks for the help, I was finally able to get it to work with this code.
import numpy as np
import cv2
import os
image_path = input("Enter a fully qualified path for an image: ")
#define a function to load an image
def img_loader(img_path):
exists = os.path.isfile(img_path)
if exists:
img = cv2.imread(img_path)
print("Success! The image path exists")
return img
else:
print("WARNING: The file path you entered was incorrect.")
return None
load=img_loader(image_path)
print(load)
I named all of the files in my folder, yet when I run the code it simply returns nothing as the file's filename attribute
if __name__ == '__main__':
print("Your Program Here")
images = glob.glob("uncropped/*.jpg")
for image in images:
with open(image, 'rb') as file:
img = Image.open(file)
print(img.filename)
print("open")
input()
This code returns nothing as the file name. What should I do?
The problem is you're opening the image file yourself with the built-in open() and passing that to Image.open(). Frankly, I agree the documentation is a little ambiguous about this scenario — I suppose a real file is a "file-like object".
Regardless, if you let PIL open the file it works:
import glob
from PIL import Image
folder = "*.jpg"
if __name__ == '__main__':
print("Your Program Here")
images = glob.glob(folder)
for image in images:
img = Image.open(image)
print(img.filename)
print("open")
If you really need the attribute to be there for some reason, a workaround is to just add it yourself:
if __name__ == '__main__':
print("Your Program Here")
images = glob.glob(folder)
for image in images:
with open(image, 'rb') as file:
img = Image.open(image)
img.filename = image # Manually add attribute.
print(img.filename)
print("open")