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)
Related
I am trying to remove those raster files (in tif format) with all no value data(all the value in the file is -3.4028235e+38).
However, I found the os. remove() could not work, there is no file being deleted. The print statement also didn't work.
Could somebody tell me what the problem is with the code?
Cheers
from PIL import Image
import os
import numpy
directory = 'E:/data/'
for image in os.listdir(directory):
indiv = Image.open(directory + image)
elevMax = numpy.amax(indiv)
print(directory + image)
print(str(elevMax))
if elevMax == -3.4028235e+38:
print("it had the value")
os.remove(os.path.join(directory, image))
Here are some outputs for the code:
E:/data/filteredN01E116.tif
1907.05
E:/data/filteredN01E117.tif
-3.4028235e+38
E:/data/filteredN01E118.tif
-3.4028235e+38
E:/data/filteredN01E119.tif
-3.4028235e+38
E:/data/filteredN01E120.tif
1693.56
Problem solved.
It is just the problem of the type.
if elevMax == numpy.float32(-3.4028235e+38):
print("it had the value")
os.remove(os.path.join(directory, image))
That works! Thanks for all of your comments.
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 want to check image is existing on the given path. Code snippet as follows:
if the image exists:
#business logic
else:
#set default logo
The most common way to check for the existence of a file in Python is using the exists() and isfile() methods from the os.path module in the standard library.
Using exists:
import os.path
if os.path.exists('mydirectory/myfile.png'):
#business logic
else:
#set default logo
os.path.exists('mydirectory/myfile.png') returns True if found else
False
Using isfile:
import os.path
if os.path.isfile('mydirectory/myfile.png'):
#business logic
else:
#set default logo
os.path.exists('mydirectory/myfile.png') returns True if found else
False
Alternatively you can also use try-except as shown below:
try:
f = open('myfile.png')
f.close()
except FileNotFoundError:
print('File does not exist')
You can do this using the os.path.exists() function in python. So it would be something like -
if os.path.exists('yourdirectory/yourfile.png'):
#business logic
else:
#set default logo
You can also use os.path.isfile() in a similar manner to check if it is a valid file (os.paath.exists() will return True for valid folders as well)
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.
i want capture the letters(characters & Numbers) from an image using python please help me how can i do it explain me with any sample code.
I hope this will help you out if your image is clear (positively less Noise).
Use "PyTesser" Project of Google in this Case.
PyTesser is an Optical Character Recognition module for Python.
It takes as input an image or image file and outputs a string.
You can get PyTesser from this link.
Here's an example:
>>> from pytesser import *
>>> image = Image.open('fnord.tif') # Open image object using PIL
>>> print image_to_string(image) # Run tesseract.exe on image
fnord
>>> print image_file_to_string('fnord.tif')
fnord
I use tesseract for this.
There is also a Python library for it: https://code.google.com/p/python-tesseract/
Example from the main page:
import tesseract
api = tesseract.TessBaseAPI()
api.Init(".","eng",tesseract.OEM_DEFAULT)
api.SetVariable("tessedit_char_whitelist", "0123456789abcdefghijklmnopqrstuvwxyz")
api.SetPageSegMode(tesseract.PSM_AUTO)
mImgFile = "eurotext.jpg"
mBuffer=open(mImgFile,"rb").read()
result = tesseract.ProcessPagesBuffer(mBuffer,len(mBuffer),api)
print "result(ProcessPagesBuffer)=",result
Here is my code for Python3 not using the tesseract library but the .exe file:
import os
import tempfile
def tesser_exe():
path = os.path.join(os.environ['Programfiles'], 'Tesseract-OCR', 'tesseract.exe')
if not os.path.exists(path):
raise NotImplementedError('You must first install tesseract from https://code.google.com/p/tesseract-ocr/downloads/detail?name=tesseract-ocr-setup-3.02.02.exe&can=2&q=')
return path
def text_from_image_file(image_name):
assert image_name.lower().endswith('.bmp')
output_name = tempfile.mktemp()
exe_file = tesser_exe() # path to the tesseract.exe file from
return_code = subprocess.call([exe_file, image_name, output_name, '-psm', '7'])
if return_code != 0:
raise NotImplementedError('error handling not implemented')
return open(output_name + '.txt', encoding = 'utf8').read()