Python Wand open a img file as blob, md5 is incorrect. Is this the Wand's bug? - wand

Python Wand open a img file as blob, md5 is incorrect.
with Image(filename=picture) as img:
blob = img.make_blob()
print 'blob md5', hashlib.md5(blob).hexdigest()
with open(picture, 'rb') as img:
content = img.read()
print 'content md5', hashlib.md5(content).hexdigest()

.make_blob() method does not write the exactly same binary to its source file. Use .signature property instead if you want the signature of the image pixels, not file representation.

Related

UnidentifiedImageError: cannot identify image file when running Streamlit

I'm writing some code for the Streamlit app, where I want the user to upload a .jpg image file and it gives me this error, "UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x00000293778F98B0>"
My code is as follows:
import streamlit as st
import pandas as pd
import numpy as np
from PIL import Image
st.title("Image classification Web App")
# loading images
def load_image(image):
image = image.resize((224,224))
im_array = np.array(image)/255 # a normalised 2D array
im_array = im_array.reshape(-1, 224, 224, 3) # to shape as (1, 224, 224, 3)
return im_array
...
if st.button("Try with the Default Image"):
image=load_image(Image.open('C:/Users/.../image21.jpg'))
st.subheader("Human is detected")
st.image(image)
st.image(initialize_model(model_name, image))
st.subheader("Upload an image file")
uploaded_file = st.file_uploader("Upload a JPG image file", type=["jpg", "jpeg"])
if uploaded_file:
image = load_image(Image.open(uploaded_file))
st.image(initialize_model(model_name, image))
However, I have no problem uploading an image with this line,
st.image(Image.open('C:/Users/../image21.jpg'))
Can anyone advise me whats wrong here?
Thanks.
You got that error because uploaded files in streamlit are file-like objects meaning they are not actual files. To Solve this problem, you will have to save the uploaded file to local directory, fetch the file from that directory and proceed with the rest of execution. This method gives you a total control of the file.
I will recommend you create a new function to accept and save user inputs. And after saving, return the path of the saved file, then read from that path, when that is successful, pass the file as a second argument to initialize_model.
Example:
import os
def get_user_input():
st.subheader("Upload an image file")
uploaded_file = st.file_uploader("Upload a JPG image file", type=["jpg", "jpeg"])
if uploaded_file is not None:
user_file_path = os.path.join("users_uploads/", uploaded_file.name)
with open(user_file_path, "wb") as user_file:
user_file.write(uploaded_file.getbuffer())
return user_file_path
uploaded_file = get_user_input()
if uploaded_file is not None:
image = load_image(uploaded_file)
st.image(initialize_model(model_name, image))

Convert Base64 String to Image file in Groovy

i checked with old threads but didn't find anything helpful.
i am a JD Edwards developer and we have a requirement in jde Orchestrator to process base64 string.
Can anyone help me and share full code for this?
i am new in groovy script.
def base64str = 'R0lGODlhAwADAHAAACwAAAAAAwADAIHsHCT97KYAAAAAAAACBIQRBwUAOw==' // < base64 string with 3x3 gif inside
def filename = System.properties['user.home']+'/documents/my.gif' // < filename with path
// save decoded base64 bytes into file
new File(filename).bytes = base64str.decodeBase64()
as a result you there should be a new file my.gif in current user/ documents folder
with 3x3 pixels image (43 bytes file)

Reading image file (file storage object) using OpenCV

I am sending an image by curl to flask server, i am using this curl command
curl -F "file=#image.jpg" http://localhost:8000/home
and I am trying to read the file using OpenCV on the server side.
On the server side I handle the image by this code
#app.route('/home', methods=['POST'])
def home():
data =request.files['file']
img = cv.imread(data)
fact_resp= model.predict(img)
return jsonify(fact_resp)
I am getting this error-
img = cv.imread(data)
TypeError: expected string or Unicode object, FileStorage found
How do I read the file using OpenCV on the server side?
Thanks!
I had similar issues while using opencv with flask server, for that first i saved the image to disk and read that image using saved filepath again using cv.imread()
Here is a sample code:
data =request.files['file']
filename = secure_filename(file.filename) # save file
filepath = os.path.join(app.config['imgdir'], filename);
file.save(filepath)
cv.imread(filepath)
But now i have got even more efficient approach from here by using cv.imdecode() to read image from numpy array as below:
#read image file string data
filestr = request.files['file'].read()
#convert string data to numpy array
file_bytes = numpy.fromstring(filestr, numpy.uint8)
# convert numpy array to image
img = cv.imdecode(file_bytes, cv.IMREAD_UNCHANGED)
After a bit of experimentation, I myself figured out a way to read the file using CV2.
For this I first read the image using PIL.image method
This is my code,
#app.route('/home', methods=['POST'])
def home():
data =request.files['file']
img = Image.open(request.files['file'])
img = np.array(img)
img = cv2.resize(img,(224,224))
img = cv2.cvtColor(np.array(img), cv2.COLOR_BGR2RGB)
fact_resp= model.predict(img)
return jsonify(fact_resp)
I wonder if there is any straight forward way to do this without using PIL.
So incase you want to do something like ,
file = request.files['file']
img = cv.imread(file)
then do it like this
import numpy as np
file = request.files['file']
file_bytes = np.fromfile(file, np.uint8)
file = cv.imdecode(file_bytes, cv.IMREAD_COLOR)
Now you don't need to do cv.imread() again, but can use this in the next line of codes.
This applies to OpenCV v3.x and onwards
Two-line solution, change grayscale to what you need
file_bytes = numpy.fromfile(request.files['image'], numpy.uint8)
# convert numpy array to image
img = cv.imdecode(file_bytes, cv.IMREAD_GRAYSCALE)

Error Converting Apps Script Blob from PNG to JPEG

I'm trying to download a PNG image in Apps Script, convert it to JPEG, and generate a data URI for this new JPEG.
function test() {
var blob = UrlFetchApp.fetch('https://what-if.xkcd.com/imgs/a/156/setup.png').getBlob();
var jpeg = blob.getAs("image/jpeg");
var uri = 'data:image/jpeg;base64,' + Utilities.base64Encode(jpeg.getBytes());
Logger.log(uri);
}
When I run this, I get:
The image you are trying to use is invalid or corrupt.
Even something like:
function test() {
var bytes = UrlFetchApp.fetch('https://what-if.xkcd.com/imgs/a/156/setup.png').getBlob().getBytes();
var jpeg = Utilities.newBlob(bytes, MimeType.PNG).getAs(MimeType.JPEG);
DriveApp.createFile(jpeg);
}
doesn't work.
Your code is correct. This may be a bug, but it's specific to the file you are using, so may as well be a bug in the file (i.e., the file could indeed be corrupted somehow). Or maybe it uses some features of PNG format that Google doesn't handle. Replacing the URL by another one, e.g.,
var blob = UrlFetchApp.fetch('https://cdn.sstatic.net/Sites/mathematica/img/logo#2.png').getBlob();
both functions work as expected.

ruby base64 decode function limited 4KB in Windows

I want to write png file from A xml including encoded png image by base64. First I tried like this
if (captureImageB64.length > 1)
pngFile = File.new("xxx.png", "wb")
captureImageB64.unpack('m').first
pngFile.close
end
but this code makes 4KB png image. captureImageB64.unpack('m').first.length is 4096. so.. next version is
if (captureImageB64.length > 1)
pngFile = File.new("xxx.png", "wb")
i = 0
while i < captureImageB64.length
pngFile.write(captureImageB64.slice(i, 12).unpack('m').first)
i += 12
end
pngFile.close
end
it makes broken png file. until 4096 is fine. How can I write the right file ?
I'm working on Windows7, ruby 2.0(x86).
Update:
I found padding string(==) in image file encoded base64. So it was encoded each 4096 byte! No one told me about that... I'll make a new encoder component.

Resources