PIL save using file object without filename - save

save() has a param fp: A filename (string), pathlib.Path object or file object. If I use file object,what is the filename ? I am inconvenient to test this,please help me!
s = io.BytesIO()
pi = Image.frombytes(mode=i.mode, size=i.size, data=i.data)
pi.save(s, format="jpeg")

Does this help?
from io import BytesIO
from PIL import Image, ImageDraw
image = Image.new("RGB", (300, 50))
draw = ImageDraw.Draw(image)
draw.text((0, 0), 'BytesIO')
byte_io = BytesIO()
image.save(byte_io, 'PNG')
with open('test.png', 'wb') as outfile:
outfile.write(byte_io.getvalue())
You still have to do something with the stream like writing to a file after declaring it.
If you want to save the bytes for something:
with io.BytesIO() as output:
image.save(output, 'PNG')
content = output.getvalue()

Related

h5py reading raw data with escape characters

Hi I want to read the hdf5 file data as it is written
But when I read it with the following code I get the following output
COde
hf = h5py.File('Json.h5', 'r')
data_read = hf.get("BinaryData_metadata")
rmdwrite = open("Test.json", "w")
rmdwrite.write(str(np.array(data_read)))
rmdwrite.close()
hf.close()
Output
[b'{\n\t"TestReport": {\n\t\t"TestName": "XYZ",\n\t\t"Description"................
How to get the exact output with the same formatting in my output file?
When I print with this
Data_arr = str(np.array(data_read))
Data_arr = repr(Data_arr)
I get
'[b\'{\\n\\t"TestReport": {\\n\\t\\t"Te................
OKey this is how I am writing the data via C++
DataSpace dataspace(1, dimsf); //Creating Dataspace
StrType datatype(PredType::C_S1); //Creating Datatype of type char
datatype.setOrder(order); //Data Store Order
datatype.setSize(file_datastring.length()); //Datalength
datatype.setCset(H5T_CSET_UTF8);
DataSet dataset = Hdf5::fileObject.createDataSet(WriteDataSet, datatype, dataspace); //Create dataset
dataset.write(file_datastring, datatype); //Write to dataset
is there something here which is appending that extra \
The solution which I found was
hf = h5py.File(H5FileName, 'r')
FileObj = open(OutFileName, "w")
hf.get(H5DataSetName).value.tofile(FileObj)
FileObj.close()
hf.close()
This works perfectly
Regards.
Siddharth

Getting error - 'PngImageFile' object has no attribute 'shape' on transferring video frames from client to flask server using Socketio

My application is to switch on cam on the client-side, take the frame, perform the ML process on it in the backend and throw it back to the client.
This part of the code (in bold) is throwing error - PngImageFile' object has no attribute 'shape'.
This code line has a problem - frame = imutils.resize(pimg, width=700)
I guess some processing is not in the right format. Please guide
#socketio.on('image')
def image(data_image):
sbuf = io.StringIO()
sbuf.write(data_image)
# decode and convert into image
b = io.BytesIO(base64.b64decode(data_image))
pimg = Image.open(b)
# Process the image frame
frame = imutils.resize(**pimg,** width=700)
frame = cv2.flip(frame, 1)
imgencode = cv2.imencode('.jpg', frame)[1]
# base64 encode
stringData = base64.b64encode(imgencode).decode('utf-8')
b64_src = 'data:image/jpg;base64,'
stringData = b64_src + stringData
# emit the frame back
emit('response_back', stringData)
The problem is that pimg is in PIL image format. While imutils.resize function expects the image in Numpy array format. So, after pimg = Image.open(b) line you need to convert the PIL image to Numpy array like below:
pimg = np.array(pimg)
For this you have to import numpy library like below:
import numpy as np
Try this out. This helped for a similar problem for me.
img_arr = np.array(img.convert("RGB"))
The problem was in the mode of the image. I had to convert it from 'P' to 'RGB'.
print(img)
>> <PIL.PngImagePlugin.PngImageFile image mode=P size=500x281 at 0x7FE836909C10>

Tesseract fails to parse text from image

I'm completely new to opencv and tesseract.
I spent all day trying to make code that would parse game duration from images like that: original image (game duration is in the top left corner)
I came to code that manages to recognize the duration sometimes (about 40% of all cases). Here it is:
try:
from PIL import Image
except ImportError:
import Image
import os
import cv2
import pytesseract
import re
import json
def non_digit_split(s):
return filter(None, re.split(r'(\d+)', s))
def time_to_sec(min, sec):
return (int(min) * 60 + int(sec)).__str__()
def process_img(image_url):
img = cv2.resize(cv2.imread('./images/' + image_url), None, fx=5, fy=5, interpolation=cv2.INTER_CUBIC)
str = pytesseract.image_to_string(img)
if "WIN " in str:
time = list(non_digit_split(str.split("WIN ",1)[1][0:6].strip()))
str = time_to_sec(time[0], time[2])
else:
str = 'Not recognized'
return str
res = {}
img_list = os.listdir('./images')
print(img_list)
for i in img_list:
res[i] = process_img(i)
with open('output.txt', 'w') as file:
file.write(json.dumps(res))
Don't even ask how I came to resizing image, but it helped a little.
I also tried to crop image first like that:
cropped image
but tesseract couldn't find any text here.
I'm sure that the issue I'm trying to solve is pretty easy. Can you please point me the right direction? How should I preprocess it so tesseract will parse it right?
Thanks to #DmitriiZ comment I managed to produce working piece of code.
I made a preprocessor that outputs something like that:
Preprocessed image
Tesseract handles it just fine.
Here is the full code:
try:
from PIL import Image
except ImportError:
import Image
import os
import pytesseract
import json
def is_dark(image):
pixels = image.getdata()
black_thresh = 100
nblack = 0
for pixel in pixels:
if (sum(pixel) / 3) < black_thresh:
nblack += 1
n = len(pixels)
if (nblack / float(n)) > 0.5:
return True
else:
return False
def preprocess(img):
basewidth = 500
wpercent = (basewidth/float(img.size[0]))
hsize = int((float(img.size[1])*float(wpercent)))
#Enlarging image
img = img.resize((basewidth,hsize), Image.ANTIALIAS)
#Converting image to black and white
img = img.convert("1", dither=Image.NONE)
return img
def process_img(image_url):
img = Image.open('./images/' + image_url)
#Area we need to crop can be found in one of two different areas,
#depending on which team won. You can replace that block and is_dark()
#function by just img.crop().
top_area = (287, 15, 332, 32)
crop = img.crop(top_area)
if is_dark(crop):
bot_area = (287, 373, 332, 390)
crop = img.crop(bot_area)
img = preprocess(crop)
str = pytesseract.image_to_string(img)
return str
res = {}
img_list = os.listdir('./images')
print(img_list)
for i in img_list:
res[i] = process_img(i)
with open('output.txt', 'w') as file:
file.write(json.dumps(res))

Open CV error--Face Recognition on MAC

I have a facedetection training code. It gives me some issues and i have no clue why.
I am using a MAC and seems like there is missing something. Can you please advise what should i do?
Thank you in advance
OpenCV(3.4.1) Error: Assertion failed (!empty()) in detectMultiScale, file /tmp/opencv-20180426-73279-16a912g/opencv-3.4.1/modules/objdetect/src/cascadedetect.cpp, line 1698
Traceback (most recent call last):
File "/Users/Desktop/OpenCV-Python-Series-master/src/faces-train.py", line 36, in <module>
faces = face_cascade.detectMultiScale(image_array, scaleFactor=1.5, minNeighbors=5)
cv2.error: OpenCV(3.4.1) /tmp/opencv-20180426-73279-16a912g/opencv-3.4.1/modules/objdetect/src/cascadedetect.cpp:1698: error: (-215) !empty() in function detectMultiScale
[Finished in 0.421s]
And my code is below.
import cv2
import os
import numpy as np
from PIL import Image
import pickle
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
image_dir = os.path.join(BASE_DIR, "images")
face_cascade = cv2.CascadeClassifier('cascades/data/haarcascade_frontalface_alt2.xml')
recognizer = cv2.face.LBPHFaceRecognizer_create()
current_id = 0
label_ids = {}
y_labels = []
x_train = []
for root, dirs, files in os.walk(image_dir):
for file in files:
if file.endswith("png") or file.endswith("jpg"):
path = os.path.join(root, file)
label = os.path.basename(root).replace(" ", "-").lower()
#print(label, path)
if not label in label_ids:
label_ids[label] = current_id
current_id += 1
id_ = label_ids[label]
#print(label_ids)
#y_labels.append(label) # some number
#x_train.append(path) # verify this image, turn into a NUMPY arrray, GRAY
pil_image = Image.open(path).convert("L") # grayscale
size = (550, 550)
final_image = pil_image.resize(size, Image.ANTIALIAS)
image_array = np.array(final_image, "uint8")
#print(image_array)
faces = face_cascade.detectMultiScale(image_array, scaleFactor=1.5, minNeighbors=5)
for (x,y,w,h) in faces:
roi = image_array[y:y+h, x:x+w]
x_train.append(roi)
y_labels.append(id_)
#print(y_labels)
#print(x_train)
with open("pickles/face-labels.pickle", 'wb') as f:
pickle.dump(label_ids, f)
recognizer.train(x_train, np.array(y_labels))
recognizer.save("recognizers/face-trainner.yml")
The assertion which fails indicates that your cascade is not loaded correctly. You can verify it by calling face_cascade.empty() just after the constructor. Please make sure that the path you provided ('cascades/data/haarcascade_frontalface_alt2.xml') is correct. When it points to a not existing file then there is no exception thrown by the constructor so you can easily miss it without calling empty() explicitly.

How to use the dart:html library to write files?

Can someone please tell me how to create a file and make it available for download via browser button?
I have read about FileWriter but not found any proper example how to use it
and I found a post How to use the dart:html library to write html files?
but the answer just refers to html5lib which just answers how to parse a String to HTML but not how to save as a file.
help appreciated. Am I missing something or there is no example for that usecase??
Personally, I use a combination of Blob, Url.createObjectUrlFromBlob And AnchorElement (with download and href properties) to create a downloadable file.
Very simple example:
// Assuming your HTML has an empty anchor with ID 'myLink'
var link = querySelector('a#myLink') as AnchorElement;
var myData = [ "Line 1\n", "Line 2\n", "Line 3\n"];
// Plain text type, 'native' line endings
var blob = new Blob(myData, 'text/plain', 'native');
link.download = "file-name-to-save.txt";
link.href = Url.createObjectUrlFromBlob(blob).toString();
link.text = "Download Now!";
As alluded to by Günter Zöchbauer's comment, an alternative to using Blobs is to base64-encode the data and generate a data URL yourself (at least for file sizes that are well within the data URL limits of most browsers). For example:
import 'dart:html';
Uint8List generateFileContents() { ... }
void main() {
var bytes = generateFileContents();
(querySelector('#download-link') as AnchorElement)
..text = 'Download File'
..href = UriData.fromBytes(bytes).toString()
..download = 'filename';
}
Also note that if you do want to use a Blob and want to write binary data from a Uint8List, you are expected to use Blob([bytes], ...) and not Blob(bytes, ...). For example:
var bytes = generateFileContents();
var blob = Blob([bytes], 'application/octet-stream');
(querySelector('#download-link') as AnchorElement)
..text = 'Download File'
..href = Url.createObjectUrlFromBlob(blob)
..download = 'filename';

Resources