ImageReader method of reportlab library does not work - python

reportlab ImageReader('url') of PIL library does not work.
my env: Python 3.7.6, Pillow 7.0.0, reportlab 3.5.32 (i tried also different version of PIL and reportlab... same error)
img = ImageReader('https://www.google.it/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png')
my error
Cannot open resource "https://www.google.it/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"
fileName='https://www.google.it/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png' identity=[ImageReader#0x119474090 filename='https://www.google.it/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png']

Solved...Solution using urls images inside tables on reportlab:
from PIL import Image as pillowImage
from django.core.files.storage import default_storage
from io import BytesIO
from reportlab.platypus import Image
cloud_image = default_storage.open('url') # using s3Storage
img = pillowImage.open(cloud_image)
img_byte_arr = BytesIO()
img.save(img_byte_arr, format=img.format)
result = Image(img_byte_arr, w * cm, h * cm)
....
data1 = [[result]]
t1 = Table(data1, colWidths=(9 * cm))
t1.setStyle(TableStyle([('VALIGN', (0, 0), (-1, -1), 'LEFT'),]))
t1.hAlign = 'LEFT'
story.append(t1)
...

Related

Display a stream images in Google Colab using OpenCV

I have a stream of images and have to display it in Google Colab notebook such that it looks like a video, But what I get is a image under image ...
from google.colab import drive
drive.mount('/content/drive')
# importing cv2
import cv2
import imutils
from google.colab.patches import cv2_imshow
from IPython.display import clear_output
import os
folder = r'/content/drive/images/'
for filename in os.listdir(folder) :
VALID_FORMAT = (".jpg", ".JPG", ".jpeg", ".JPEG", ".png", ".PNG")
if filename.upper().endswith(VALID_FORMAT):
path = folder + filename
image = cv2.imread(path)
# resize image
frame = imutils.resize(image, width=1200)
# show the image
cv2_imshow(frame)
cv2.waitKey(20)
I don't know if some function can display image in the same place.
But I have code which I used with cv2 to display frames from webcam as video.
Here reduced version.
imshow(name, image) creates <img id="name"> and replaces src/url with image converted to string base64 and browser shows it as image.
imshow() uses name to check if already exist <img id="name"> and it replaces previous image.
from IPython.display import display, Javascript
from google.colab.output import eval_js
from base64 import b64encode
import cv2
def imshow(name, img):
"""Put frame as <img src="data:image/jpg;base64,...."> """
js = Javascript('''
async function showImage(name, image, width, height) {
img = document.getElementById(name);
if(img == null) {
img = document.createElement('img');
img.id = name;
document.body.appendChild(img);
}
img.src = image;
img.width = width;
img.height = height;
}
''')
height, width = img.shape[:2]
ret, data = cv2.imencode('.jpg', img) # compress array of pixels to JPG data
data = b64encode(data) # encode base64
data = data.decode() # convert bytes to string
data = 'data:image/jpg;base64,' + data # join header ("data:image/jpg;base64,") and base64 data (JPG)
display(js)
eval_js(f'showImage("{name}", "{data}", {width}, {height})') # run JavaScript code to put image (JPG as string base64) in <img>
# `name` and `data` in needs `" "` to send it as text, not as name of variabe.
And here code which uses it to display image Lenna from Wikipedia.
import requests
import cv2
import numpy as np
import time
url = 'https://upload.wikimedia.org/wikipedia/en/7/7d/Lenna_%28test_image%29.png'
data = requests.get(url)
frame1 = cv2.imdecode(np.frombuffer( data.content, np.uint8), 1)
frame2 = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)
for _ in range(3):
imshow("temp", frame1)
time.sleep(1)
imshow("temp", frame2)
time.sleep(1)
EDIT
Display images in two "windows" using imshow("img1", ...) and imshow("img2", ...)
import os
import cv2
import imutils
import time
folder = r'/content/drive/images/'
VALID_FORMAT = (".JPG", ".JPEG", ".PNG")
for number, filename in enumerate(os.listdir(folder)):
if filename.upper().endswith(VALID_FORMAT):
path = os.path.join(folder, filename)
image = cv2.imread(path)
frame = imutils.resize(image, width=400)
number = number % 2
imshow(f"img{number}", frame)
time.sleep(1)

python code for downloading images from image-net.org for haar cascade training

I have a python code for downloading images from "www.image-net.org" for haar cascade training. Basically it checks each image urls and download the images.
import urllib2
import cv2
import numpy as np
import os
import urllib
import sys
reload(sys)
sys.setdefaultencoding('utf8')
def store_raw_images():
pos_images_link = 'http://www.image-net.org/api/text/imagenet.synset.geturls?wnid=n04154340'
pos_image_urls = urllib2.urlopen(pos_images_link).read().decode()
if not os.path.exists('pos'):
os.makedirs('pos')
pic_num = 1
for i in pos_image_urls.split('\n'):
try:
print(i)
urllib.urlretrieve(i, "pos/"+str(pic_num)+".jpg")
img = cv2.imread("pos/"+str(pic_num)+".jpg",cv2.IMREAD_GRAYSCALE)
# should be larger than samples / pos pic (so we can place our image on it)
resized_image = cv2.resize(img, (100, 100))
cv2.imwrite("pos/"+str(pic_num)+".jpg",resized_image)
pic_num += 1
except Exception as e:
print(str(e))
store_raw_images()
I copy paste the url link to download in "pos_images_link", but the code only checks the urls of 5 images then the code stops running with a message in the terminal:
"terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::substr: __pos (which is 140) > this->size() (which is 0)"
, i am using opencv 3.1.0 and python 2.7.12
The follows worked in python 3 with opencv
from urllib.request import Request, urlretrieve
import cv2
import numpy as np
import os
import urllib
import sys
def store_raw_images():
url = 'http://www.image-net.org/api/text/imagenet.synset.geturls?wnid=n04154340'
request = urllib.request.Request(url)
response = urllib.request.urlopen(request)
urls = response.read().decode('utf-8')
if not os.path.exists('pos'):
os.makedirs('pos')
pic_num = 1
for i in urls.split('\n'):
try:
print(i)
urlretrieve(i, "pos/"+str(pic_num)+".jpg")
img = cv2.imread("pos/"+str(pic_num)+".jpg",cv2.IMREAD_GRAYSCALE)
# should be larger than samples / pos pic (so we can place our image on it)
resized_image = cv2.resize(img, (100, 100))
cv2.imwrite("pos/"+str(pic_num)+".jpg",resized_image)
pic_num += 1
except Exception as e:
print(str(e))
store_raw_images()

Using def function to call image from urllib import urlopen - python 2.7

I have made def function to call JPG image to display easily but it in not working property. Also I don't want to use urllib2. It says image_file = image_to_PhotoImage(image)
NameError: name 'image' is not defined
Any suggestions? Thank you
from urllib import urlopen
from Tkinter import *
def image_to_PhotoImage(image, width = None, height = None):
# Import the Python Imaging Library, if it exists
try:
from PIL import Image, ImageTk
except:
raise Exception, 'Python Imaging Library has not been installed properly!'
# Import StringIO for character conversions
from StringIO import StringIO
# Convert the raw bytes into characters
image_chars = StringIO(image)
# Open the character string as a PIL image, if possible
try:
pil_image = Image.open(image_chars)
except:
raise Exception, 'Cannot recognise image given to "image_to_Photoimage" function\n' + \
'Confirm that image was downloaded correctly'
# Resize the image, if a new size has been provided
if type(width) == int and type(height) == int and width > 0 and height > 0:
pil_image = pil_image.resize((width, height), Image.ANTIALIAS)
# Return the result as a Tkinter PhotoImage
return ImageTk.PhotoImage(pil_image)
import Tkinter as tk
root = tk.Tk()
url = "http://www.online-image-editor.com//styles/2014/images/example_image.png"
gogo = urlopen(url)
data_stream = gogo.read()
gogo.close()
image_file = image_to_PhotoImage(image1)
label = tk.Label(root, image=image_file, bg='black')

Windows Python Code not working on Linux Debian

The code generates a QR code and prints it, but It is not working on the Debian Os due to not supporting the imported libraries (win32print, Win32ui).
Can anyone tell me how to run it on the Debian without changing the whole code.
from random import randint
import win32print
import win32ui
from PIL import Image, ImageWin
from PIL._imaging import font
from PIL import ImageFont
from PIL import ImageDraw
HORZRES = 8
VERTRES = 10
LOGPIXELSX = 88
LOGPIXELSY = 90
PHYSICALWIDTH = 110
PHYSICALHEIGHT = 111
PHYSICALOFFSETX = 112
PHYSICALOFFSETY = 113
__author__ = 'masoodhussain'
import qrcode
import subprocess
import os
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
qr.add_data('Masooddkjfdlfs,kokdfds sddshfhkjshfljsdhkjfdrtyyhtfhfghgh3')
qr.make(fit=True)
"subprocess.call(['lp', 'foo.png'])"
printer_name = win32print.GetDefaultPrinter()
img = qr.make_image()
img.show()
random_number= randint(0,10000)
img.save('label_'+str(random_number)+'.png')
file_name = 'label_'+str(random_number)+'.png'
print(file_name)
hDC = win32ui.CreateDC ()
hDC.CreatePrinterDC (printer_name)
printable_area = hDC.GetDeviceCaps (HORZRES), hDC.GetDeviceCaps (VERTRES)
printer_size = hDC.GetDeviceCaps (PHYSICALWIDTH), hDC.GetDeviceCaps (PHYSICALHEIGHT)
printer_margins = hDC.GetDeviceCaps (PHYSICALOFFSETX), hDC.GetDeviceCaps (PHYSICALOFFSETY)
bmp = Image.open (file_name)
if bmp.size[0] > bmp.size[1]:
bmp = bmp.rotate (90)
ratios = [1.0 * printable_area[0] / bmp.size[0], 1.0 * printable_area[1] / bmp.size[1]]
scale = min (ratios)
hDC.StartDoc (file_name)
hDC.StartPage ()
dib = ImageWin.Dib (bmp)
scaled_width, scaled_height = [int (scale * i) for i in bmp.size]
x1 = int ((printer_size[0] - scaled_width) / 2)
y1 = int ((printer_size[1] - scaled_height) / 2)
x2 = x1 + scaled_width
y2 = y1 + scaled_height
dib.draw (hDC.GetHandleOutput (), (x1, y1, x2, y2))
hDC.EndPage ()
hDC.EndDoc ()
hDC.DeleteDC ()
when I run the code by removing the unsupported libraries it gives an error on this part: error importing
import qrcode
I am trying to import whole folder for using there other files. In Windows it was working perfectly. Any help would be appreciated.Thanks
This code is equivalent to the code posted in Question.
from random import randint
import cups
from PIL import Image, ImageWin
from PIL._imaging import font
from PIL import ImageFont
from PIL import ImageDraw
__author__ = 'masoodhussain'
import qrcode
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=5,
border=2,
)
qr.add_data('localhost:5070productinfo')
qr.make(fit=True)
conn= cups.Connection()
printer_name = conn.getPrinters()
printer_name = printer_name.keys()[0]
printqueuelength = len(conn.getJobs())
img = qr.make_image()
img.show()
random_number= randint(0,10000)
img.save('label_'+str(random_number)+'.png')
file_name = 'label_'+str(random_number)+'.png'
print(file_name)
conn.printFile(printer_name,file_name,"Hello", options ={'media':'25x25mm'})
Important part is the installation of required libraries and changing your media to the required size.
Even if you install qrcode, your code will still fail because of the Windows specific library. You need to check on which system you are working and preferably put the whole print function in a separate function.
Here are some useful links: https://stackoverflow.com/a/1857/2776376 and https://pypi.python.org/pypi/pycups
import platform
if platform.system() = 'Linux':
import libcups
elif platform.system() = 'Windows':
import win32print
import win32ui
else:
print('Unsupported OS. Exiting....')
sys.exit(1)
def my_printer_function():
if platform.system() = 'Linux':
#now call the Linux printer
elif platform.system() = 'Windows':
#use your old Windows code

img = Image.open(fp) AttributeError: class Image has no attribute 'open'

I want to put the pictures into a PDF file. My code follows...
import sys
import xlrd
from PIL import Image
import ImageEnhance
from reportlab.platypus import *
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.rl_config import defaultPageSize
PAGE_HEIGHT=defaultPageSize[1]
styles = getSampleStyleSheet()
Title = "Integrating Diverse Data Sources with Gadfly 2"
Author = "Aaron Watters"
URL = "http://www.chordate.com/"
email = "arw#ifu.net"
from reportlab.lib.units import inch
pageinfo = "%s / %s / %s" % (Author, email, Title)
def myFirstPage(canvas, doc):
canvas.saveState()
#canvas.setStrokeColorRGB(1,0,0)
#canvas.setLineWidth(5)
#canvas.line(66,72,66,PAGE_HEIGHT-72)
canvas.setFont('Times-Bold',16)
canvas.drawString(108, PAGE_HEIGHT-108, Title)
canvas.setFont('Times-Roman',9)
canvas.drawString(inch, 0.75 * inch, "First Page / %s" % pageinfo)
canvas.restoreState()
def myLaterPages(canvas, doc):
#canvas.drawImage("snkanim.gif", 36, 36)
canvas.saveState()
#canvas.setStrokeColorRGB(1,0,0)
#canvas.setLineWidth(5)
#canvas.line(66,72,66,PAGE_HEIGHT-72)
canvas.setFont('Times-Roman',9)
canvas.drawString(inch, 0.75 * inch, "Page %d %s" % (doc.page, pageinfo))
canvas.restoreState()
def go():
Elements.insert(0,Spacer(0,inch))
doc = SimpleDocTemplate('ss.pdf')
doc.build(Elements,onFirstPage=myFirstPage, onLaterPages=myLaterPages)
Elements = []
HeaderStyle = styles["Heading1"] # XXXX
def header(txt, style=HeaderStyle, klass=Paragraph, sep=0.3):
s = Spacer(0.2*inch, sep*inch)
Elements.append(s)
para = klass(txt, style)
Elements.append(para)
ParaStyle = styles["Normal"]
def p(txt):
return header(txt, style=ParaStyle, sep=0.1)
def open_excel(file= 'exc.xls'):
try:
data = xlrd.open_workbook(file)
return data
except Exception,e:
print str(e)
#pre = p # XXX
PreStyle = styles["Code"]
def pre(txt):
s = Spacer(0.1*inch, 0.1*inch)
Elements.append(s)
p = Preformatted(txt, PreStyle)
Elements.append(p)
p("""\
Relational databases manipulate and store persistent
table structures called relations, such as the following
three tables""")
fp = open("/pdf-ex/downloadwin7.png","rb")
img = Image.open(fp)
img.show()
# HACK
Elements.append(PageBreak())
go()
You have a namespace conflict. One of your import statements is masking PIL.Image (which is a module, not a class) with some class named Image.
Instead of ...
from PIL import Image
try ...
import PIL.Image
then later in your code...
fp = open("/pdf-ex/downloadwin7.png","rb")
img = PIL.Image.open(fp)
img.show()
When working with a LOT of imports, beware of namespace conflicts. I'm generally very wary of from some_module import * statements.
Good luck with your project and happy coding.
I had a similar problem with TKInter in a single file:
I changed:
from PIL import ImageTk, Image
from tkinter import *
to:
from tkinter import *
from PIL import ImageTk, Image
and the problem went away.
This is the only solution I could find.
try:
from PIL import Image
except ImportError:
import Image

Categories

Resources