I am trying to adjust the size of a barcode output
import barcode
from barcode.writer import ImageWriter
bar_class = barcode.get_barcode_class('code128')
barcode = '1234567890'
writer=ImageWriter()
writer.set_options({module_width:2, module_height:2})
code128 = bar_class(barcode, writer)
code128.save('filename')
The error I am getting is:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'module_width' is not defined
I dont really understand how to use the documentation found here: https://pythonhosted.org/pyBarcode/writers/index.html
After you generated an image of any size you can resize it using PIL
import barcode
from barcode.writer import ImageWriter
import PIL
from PIL import Image
bar_class = barcode.get_barcode_class('code128')
barcode = '1234567890'
writer=ImageWriter()
code128 = bar_class(barcode, writer)
code128.save('filename') # save the originally generated image
to_be_resized = Image.open('filename.png') # open in a PIL Image object
newSize = (500, 300) # new size will be 500 by 300 pixels, for example
resized = to_be_resized.resize(newSize, resample=PIL.Image.NEAREST) # you can choose other :resample: values to get different quality/speed results
resized.save('filename_resized.png') # save the resized image
more on PIL.Image.resize
I solved this problem by changing this line
code128.save('filename', {"module_width":0.35, "module_height":10, "font_size": 18, "text_distance": 1, "quiet_zone": 3})
without using another liabrary.
See that!
I solved my problem exactly like this, when saving, I did it as follows::
IMPORTANT: Without another library!
ean = barcode.get('ean13', setbarcodehere, writer=ImageWitoutTextWriter())
filename = ean.save(setfilenamehere, {"module_width":0.35, "module_height":10, "font_size": 18, "text_distance": -3, "quiet_zone": 1})
filename
print('Done! :D, {}'.format(filename))
Example:
Related
Basically, I copied and paste a script, and merged it with other script, and now the script doesn't work, it says an error "NoneType object has no attribute save"Screenshot
And here's the script:
` from PIL import Image
import PIL
import os
from glob import glob
imgs = [y for x in os.walk(".") for y in glob(os.path.join(x[0], '*.png'))]
size = 32, 32
lastdir = None
for file in imgs:
img = Image.open(file)
img = img.thumbnail(size, resample=PIL.Image.NEAREST)
file = file.replace('img', 'icon', 1)
dir = os.path.dirname(file)
try:
os.makedirs(dir)
except:
pass
if dir!=lastdir:
print(dir)
lastdir = dir
img.save(file + ".png", "PNG")`
Resize various images on various directories and save them, but the images are not saving.
The thumbnail() method modifies its object rather than returning a new one. So, this line:
img = img.thumbnail(size, resample=PIL.Image.NEAREST)
should be:
img.thumbnail(size, resample=PIL.Image.NEAREST)
I'm creating a plot in R, but then trying to return the resulting image data to Python so that Python can display the image.
Within R, I've used the magick library to hold the image in memory (instead of plotting to the screen).
"We use image_write to export an image in any format to a file on disk, or in memory if path = NULL"
I'm unsure how to process either the SexpExtPtr or ByteVector types that are returned by rpy2 to Python.
import rpy2.robjects as ro
r = ro.r
r('''
library("magick")
figure <- image_graph(width = 400, height = 400, res = 96)
plot(c(1,2,3))
image <- image_write(figure, path = NULL, format = "png")
# image_write(figure, path = 'example.png', format = 'png')
''')
figure = ro.globalenv['figure']
image = ro.globalenv['image']
im = Image.open(BytesIO(image))
The code above gives me the error:
Traceback (most recent call last):
File "stackoverflow.py", line 23, in <module>
im = Image.open(BytesIO(image))
TypeError: a bytes-like object is required, not 'ByteVector'
In Python:
figure has type <class 'rpy2.rinterface.SexpExtPtr'>
image has type <class 'rpy2.robjects.vectors.ByteVector'>
So... it turns out that <class 'rpy2.robjects.vectors.ByteVector'> is an iterable and I can use bytes() to construct an array of bytes.
Also, by putting the code inside a function that uses return to return the PIL image I can get the image to display within a Jupyter notebook (alternatively we could just do image.show())
from io import BytesIO
import PIL.Image as Image
import rpy2.robjects as ro
def main():
r = ro.r
r('''
library("magick")
figure <- image_graph(width = 400, height = 400, res = 96)
plot(c(1,2,3))
image <- image_write(figure, path = NULL, format = "png")
image_write(figure, path = 'example.png', format = 'png')
''')
image_data = ro.globalenv['image']
image = Image.open(BytesIO(bytes(image_data)))
return image
if __name__ == '__main__':
image = main()
image.show()
I have been attempting to produce an OCR tool following this tutorial on youtube, and using the following script:
import os
import sys
import cv2
import numpy as np
input_f = 'letter.data'
img_resize_factor = 12
start, end = 6, -1
height, width = 16, 8
with open(input_f, 'r') as f:
for line in f.readlines():
data = np.array([255*float(x) for x in line.split('\t')[start:end]])
img = np.reshape(data, (height, width))
img_scaled = cv2.resize(img, None, fx=img_resize_factor, fy=img_resize_factor)
print(line)
cv2.imshow('img', img_scaled)
c = cv2.waitKey()
if c == 27:
break
The code falls over when attempting to use cv2.imshow('img', img_scaled) the window appears however is non responding and the image is not loaded into it.
I am using the most up to date version of OpenCV, I am running this in VisualStudio, and have had to add "python.linting.pylintArgs": ["--extension-pkg-whitelist=cv2"] to the user settings.
The error I get is:
Exception has occurred: cv2.error OpenCV(4.0.0)
c:\projects\opencv-python\opencv\modules\imgproc\src\color.hpp:261:
error: (-2:Unspecified error) in function '__cdecl
cv::CvtHelper,struct cv::Set<3,4,-1>,struct
cv::Set<0,2,5>,2>::CvtHelper(const class cv::_InputArray &,const class
cv::_OutputArray &,int)' > Unsupported depth of input image: >
'VDepth::contains(depth)' > where > 'depth' is 6 (CV_64F) File
"C:\Users\aofarrell\Desktop\Python\NeuralNetworks\SimpleOCR.py", line
23, in
break
Everything in your script is wrong.
Solution
1) If you are opening a file, open just file, get data and get out of with statement
2) The error you are experiencing is due to wrong shape
I opened the file and extracted images
import os
import sys
import cv2
import numpy as np
input_f = 'letter.data'
start, end = 6, -1
def file_opener(input_f):
with open(input_f,'r') as fl:
for line in fl.readlines():
yield np.array([255*float(x) for x in line.split('\t')[start:-1]])
iterator = file_opener(input_f)
images = np.array([row for row in iterator]).reshape(52152,16,8) # array with 52152 images
for image_index in range(images.shape[0]):
IMAGE = cv2.resize(images[image_index,:],(0,0),fx=5,fy=5)
cv2.imshow('image {}/{}'.format(image_index,images.shape[0]),IMAGE)
cv2.waitKey(0)
cv2.destroyAllWindows(0)
I am working on an art project and am converting text to binary to images.
So far, I have what I think is the hard part done and am almost there ...
except i'm not quite sure how to approach this last bit of the problem:
I have a series of images displayed one after another but I need to wrap the images so that they are formatted to all fit on a page of A4 (printer paper) in landscape orientation.
How should I approach this?
I have the basic script to convert text to binary to images.
One additional issue I'm seeing is that when I run the script on the entire passage, too many files are opened and I receive an error(shown below):
Traceback (most recent call last):
File "ascii_to_binary.py", line 73, in <module>
imgs = [Image.open(i) for i in list_im]
File "/home/odroid/.virtualenvs/cv/local/lib/python2.7/site-packages/PIL/Image.py", line 2410, in open
fp = builtins.open(filename, "rb")
IOError: [Errno 24] Too many open files: 'open_circle.png'
Here's the script in its entirety for reference:
import numpy as np
import cv2
import imutils
import sys
from PIL import Image
open_circle = 'open_circle.png'
closed_circle = 'closed_circle.png'
diamond = 'diamond.png'
text1 = open("filename.text", "r")
letters = text1.read()
a = len(letters)
binary_text = [None]*a #pre-allocating a list
encoded_bin = ' '.join([bin(ord(letter))[2:].zfill(8) for letter in letters])
b = len(encoded_bin[0:18])
list_im = [0]*b
for val in range(b):
if encoded_bin[val] == '0':
list_im[val] = closed_circle
if encoded_bin[val] == '1':
list_im[val] = open_circle
if encoded_bin[val] == ' ':
list_im[val] = diamond
imgs = [Image.open(i) for i in list_im]
min_shape = sorted( [(np.sum(i.size), i.size) for i in imgs] )[0][1]
imgs_comb = np.hstack( (np.asarray(i.resize(min_shape)) for i in imgs) )
imgs_comb = Image.fromarray(imgs_comb)
imgs_comb.show()
I'm trying to convert a PDF to PNG - this all works fine, however, the output image is still transparent even when I believe I have disabled it:
with Image(filename='sample.pdf', resolution=300) as img:
img.background_color = Color("white")
img.alpha_channel = False
img.save(filename='image.png')
The above produces the images but are transparent, I also tried the below:
with Image(filename='sample.pdf', resolution=300, background=Color('white')) as img:
img.alpha_channel = False
img.save(filename='image.png')
which produces this error:
Traceback (most recent call last):
File "file_convert.py", line 20, in <module>
with Image(filename='sample.pdf', resolution=300, background=Color('white')) as img:
File "/Users/Frank/.virtualenvs/wand/lib/python2.7/site-packages/wand/image.py", line 1943, in __init__
raise TypeError("blank image parameters can't be used with image "
TypeError: blank image parameters can't be used with image opening parameters
I also had some PDFs to convert to PNG. This worked for me and seems simpler than compositing images, as shown above.:
from wand.image import Image
from wand.color import Color
all_pages = Image(blob=self.pdf) # PDF will have several pages.
single_image = all_pages.sequence[0] # Just work on first page
with Image(single_image) as i:
i.format = 'png'
i.background_color = Color('white') # Set white background.
i.alpha_channel = 'remove' # Remove transparency and replace with bg.
Reference: wand.image
From a previous answer, try creating an empty image with a background color, then composite over.
from wand.image import Image
from wand.color import Color
with Image(filename="sample.pdf", resolution=300) as img:
with Image(width=img.width, height=img.height, background=Color("white")) as bg:
bg.composite(img,0,0)
bg.save(filename="image.png")
Compiling the other answers, here is the function I use to convert a PDF into pages:
import os
from wand.image import Image
from wand.color import Color
def convert_pdf(filename, output_path, resolution=150):
""" Convert a PDF into images.
All the pages will give a single png file with format:
{pdf_filename}-{page_number}.png
The function removes the alpha channel from the image and
replace it with a white background.
"""
all_pages = Image(filename=filename, resolution=resolution)
for i, page in enumerate(all_pages.sequence):
with Image(page) as img:
img.format = 'png'
img.background_color = Color('white')
img.alpha_channel = 'remove'
image_filename = os.path.splitext(os.path.basename(filename))[0]
image_filename = '{}-{}.png'.format(image_filename, i)
image_filename = os.path.join(output_path, image_filename)
img.save(filename=image_filename)
The other answer (compositing with a white image) works, but only on the last page, as does setting the alpha channel directly. The following works on wand 0.4.2:
im = wand_image(filename='/tmp/foo.pdf', resolution=200)
for i, page in enumerate(im.sequence):
with wand_image(page) as page_image:
page_image.alpha_channel = False
page_image.save(filename='/tmp/foo.pdf.images/page-%s.png' % i)
I think this is probably a bug in wand. It seems like setting the alpha channel for a PDF should affect all pages, but it doesn't.
For those who are still having problem with this, I found solution (it works in version 0.4.1 and above, I am not sure about earlier versions).
So you should just use something like this:
from wand.image import Image
from wand.color import Color
with Image(filename='sample.pdf', resolution=300) as img:
img.background_color = Color("white")
img.alpha_channel = 'remove'
img.save(filename='image.png')