AttributeError: module 'tensorflow' has no attribute 'WholeFileReader' - python

I have been trying to implement this piece of code and realized a lot has been deprecated and updated in TensorFlow V2.
CODE
filenames=['images/000001.jpg','images/000002.jpg','images/000003.jpg','images/000004.jpg']
labels=[1,0,1,0]
filename_queue=tf.train.string_input_producer(filenames)
reader=tf.WholeFileReader()
filename, content = reader.read(filename_queue)
images=tf.image.decode_jpeg(content, channels=3)
images=tf.cast(images, tf.float32)
resized_images=tf.image.resize_images(images, (224, 224))
I have altered the tf.train.string_input_producer(filenames) part. But I am not able to find any alternative to tf.WholeFileReader(). Also I am using google colab and thus cannot rely on V1 as it says colab don't support TensorFlow V2.
Here's my piece of code.
My code
import os
import numpy as np
image_path = '/content/drive/MyDrive'
categ = ["IMG"]
for c in categ:
path = os.path.join(image_path, c)
for img in os.listdir(path):
image = [os.path.join(path, img)]
queue=tf.data.Dataset.from_tensor_slices(image)
reader=tf.WholeFileReader() #AttributeError
Can anyone help?

You probably should be able to find it here:
tf.io.WholeFileReader()
instead of
tf.WholeFileReader()

Related

Using PIL module to open file from GCS

I am a beginner in programming, and this is my first little try. I'm currently facing a bottleneck, I would like to ask for the help. Any advice will be welcome. Thank you in advance!
Here is what I want to do:
To make a text detection application and extract the text for the further usage(for instance, to map some of the other relevant information in a data). So, I devided into two steps:
1.first, to detect the text
2.extract the text and use the regular expression to rearrange it for the data mapping.
For the first step, I use google vision api, so I have no probelm reading the image from google cloud storage(code reference 1):
However, when it comes to step two, I need a PIL module to open the file for drawing the text. When useing the methodImage.open(), it requries a path`. My question is how do I call the path? (code reference 2):
code reference 1:
from google.cloud import vision
image_uri = 'gs://img_platecapture/img_001.jpg'
client = vision.ImageAnnotatorClient()
image = vision.Image()
image.source.image_uri = image_uri ## <- THE PATH ##
response = client.text_detection(image=image)
for text in response.text_annotations:
print('=' * 30)
print(text.description)
vertices = ['(%s,%s)' % (v.x, v.y) for v in text.bounding_poly.vertices]
print('bounds:', ",".join(vertices))
if response.error.message:
raise Exception(
'{}\nFor more info on error messages, check: '
'https://cloud.google.com/apis/design/errors'.format(
response.error.message))
code reference 2:
from PIL import Image, ImageDraw
from PIL import ImageFont
import re
img = Image.open(?) <- THE PATH ##
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("simsun.ttc", 18)
for text in response.text_annotations[1::]:
ocr = text.description
bound=text.bounding_poly
draw.text((bound.vertices[0].x-25, bound.vertices[0].y-25),ocr,fill=(255,0,0),font=font)
draw.polygon(
[
bound.vertices[0].x,
bound.vertices[0].y,
bound.vertices[1].x,
bound.vertices[1].y,
bound.vertices[2].x,
bound.vertices[2].y,
bound.vertices[3].x,
bound.vertices[3].y,
],
None,
'yellow',
)
texts=response.text_annotations
a=str(texts[0].description.split())
b=re.sub(u"([^\u4e00-\u9fa5\u0030-u0039])","",a)
b1="".join(b)
regex1 = re.search(r"\D{1,2}Dist.",b)
if regex1:
regex1="{}".format(regex1.group(0))
.........
PIL does not have built in ability to automatically open files from GCS. you will need to either
Download the file to local storage and point PIL to that file or
Give PIL a BlobReader which it can use to access the data:
from PIL import Image
from google.cloud import storage
storage_client = storage.Client()
bucket = storage_client.bucket('img_platecapture')
blob = bucket.get_blob('img_001.jpg') # use get_blob to fix generation number, so we don't get corruption if blob is overwritten while we read it.
with blob.open() as file:
img = Image.open(file)
# ...

Why is there a "ValueError: unknown file extension" when I am trying to save images into the tif file format using matplotlib?

In this code, I am trying to use a pre-loaded machine learning model and a pre-defined feature extraction function to perform image segmentation on multiple images that I have in my Train_images directory. My code runs all the way until the line "print(file)", and at that point, I am not sure what happens. This is the code I am using to go through a training set of tif image files.
import glob
import pickle
from matplotlib import pyplot as plt
filename = "sandstone_rf_model"
loaded_model = pickle.load(open(filename, 'rb'))
path = "images/Train_images/*.tif"
for file in glob.glob(path):
print(file) # just stop here to see all file names
printed
img1 = cv2.imread(file)
img = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
# Call the feature extraction function.
X = feature_extraction(img)
result = loaded_model.predict(X)
segmented = result.reshape((img.shape))
name = file.split("e_")
plt.imsave('images/Segmented/', segmented, cmap='jet')
Edit:
Previously I got a ValueError, but I changed my last line of code to the following:
plt.imsave('images/segmented_sandstone/'+name[1], segmented, cmap='jet')
Now I receive the following KeyError:
` File
"/Users/zeeshanpatel/opt/anaconda3/envs/master/lib/python3.7/site-
packages/PIL/Image.py", line 2123, in save
save_handler = SAVE[format.upper()]
KeyError: 'TIF'`
The issue is occuring in the last line of the code, please let me know how I can format this to fix this issue.
Use the tifffile library and replace the last line with tifffile.imsave, like this
import tiffile
tifffile.imsave('images/segmented_sandstone/'+name[1], segmented, cmap='jet')

imdecode returning None when using urllib

I am trying to read an img from a url. My code works when the img is coded jpeg, but, when It's .svg for example, the function imdecode from openCV just don't work. Here it is the code:
url_response = urllib.urlopen("https://upload.wikimedia.org/wikipedia/commons/a/ac/BanderaEstepa.svg")
img_array = array(bytearray(url_response.read()), dtype=uint8)
img_url = cv2.imdecode(img_array, 1)
Need help please. Thanks in advance.

No module named LBPHFacerecognizer

python version 3.6.1
numpy version 1.13.1
OpenCV version 3.3.0
import numpy as np
import cv2
import os
from PIL import Image
recognizer = cv2.createLBPHFaceRecognizer()
path = 'dataset'
def getImageWithID(path):
imagesPaths = [os.path.join(path,f) for f in os.listdir(path)]
faces = []
IDs = []
for imagePath in imagePaths:
faceImg = Image.open(imagePath)
faceNp = np.array(faceImg, 'uint8')
ID = int(os.path.split(imagePath)[-1].split(".")[1])
faces.append(faceNp)
IDs.append(ID)
cv2.imshow("training the data ", facesNp)
cv2.waitKey(10)
return IDs, faces
Ids, faces = getImageWithID(path)
recognizer.train(faces, Ids)
recognizer.save("recognizer/trainingData.yml")
cv2.destroyAllWindows()
AttributeError: module 'cv2.face' has no attribute 'createLBPHFaceRecognizer
'
Your problem is you are using Opencv 3.x. Try cv2.face.LBPHFaceRecognizer_create() for the said problem.
But if still compatibility issue persists then either add opencv_contrib module to your existing opencv 3.x version or change the opencv to older version.

python open cv loading image

I'm new to python and open cv. I'm trying to find out how to load an image in opencv with python. Can any one provide an example (with code) explaining how to load the image and display it?
import sys
import cv
from opencv.cv import *
from opencv.highgui import *
ll="/home/pavan/Desktop/iff pics/out0291.tif"
img= cvLoadImage( ll );
cvNamedWindow( “Example1”, CV_WINDOW_AUTOSIZE );
cvShowImage( “Example1”, img );
cvWaitKey(10);
cvDestroyWindow( “Example");
There have been quite a few changes in the openCV2 API:
import cv
ll = "/home/pavan/Desktop/iff pics/out0291.tif"
img = cv.LoadImage(ll)
cv.NamedWindow("Example", cv.CV_WINDOW_AUTOSIZE )
cv.ShowImage("Example", img )
cv.WaitKey(10000)
cv.DestroyWindow("Example")
It is a simpler, quite cleaner syntax!
Also, you don't need trailing ; à-la-matlab. Last, be careful about the quotes you use.
For the newer openCV3 API, you should see the other answer to this question.
import cv2
image_path = "/home/jay/Desktop/earth.jpg"
img = cv2.imread(image_path) # For Reading The Image
cv2.imshow('image', img) # For Showing The Image in a window with first parameter as it's title
cv2.waitKey(0) #waits for a key to be pressed on a window
cv2.destroyAllWindows() # destroys the window when the key is pressed
There are 2 possible approaches to this:
Using argparse (recommended):
import cv2
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required = True,help = "Path to the image")
args = vars(ap.parse_args())
image = cv2.imread(args["image"])
This will take the image as an argument, will then convert the argument, add it to ap and the load it using the imread function()
To run it.
Go to your required folder
source activate your environment
python filename.py -i img.jpg
Hardcoding the image location:
import cv2
img = cv2.imread("\File\Loca\img.jpg")
cv2.imshow("ImageName",img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Run this similarly, omitting the arguments.

Categories

Resources