Overwrite Filename of Image in Python - python

I'm using Python and I have the following snippet of code:
>>> from PIL import Image
>>> from PIL import ImageFont
>>> from PIL import ImageDraw
>>> img = Image.open("sample_in.jpg")
>>> draw = ImageDraw.Draw(img)
# font = ImageFont.truetype(<font-file>, <font-size>)
>>> font = ImageFont.truetype("sans-serif.ttf", 16)
# draw.text((x, y),"Sample Text",(r,g,b))
>>> draw.text((0, 0),"Sample Text",(255,255,255),font=font)
>>> img.save('sample_in.jpg')
source: Add Text on Image using PIL
The problem I am having is I can't rename the file the same as the original is there a way to accomplish this?
Traceback:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 1433, in save
fp = __builtin__.open(fp, "wb")
IOError: [Errno 13] Permission denied: 'sample_in.jpg'

Related

Convert to RGB returns a RGBA image

I'm trying to use Python and PIL to add some text to an image. I am failing on saving the resultant image as JPG.
I've based it on the example given on
https://pillow.readthedocs.io/en/5.2.x/reference/ImageDraw.html#example-draw-partial-opacity-text
from PIL import Image, ImageDraw, ImageFont
def example():
base = Image.open('test.jpg').convert('RGBA')
txt = Image.new('RGBA', base.size, (255,255,255,0))
fnt = ImageFont.truetype('/Library/Fonts/Chalkduster.ttf', 40)
drw = ImageDraw.Draw(txt)
drw.text((10,10), "HELLO", font=fnt, fill=(255,0,0,128))
result= Image.alpha_composite(base, txt)
result.convert('RGB')
print ('mode after convert = %s'%result.mode)
result.save('test1.jpg','JPEG')
example()
Running this prints mode after convert = RGBA
which is then followed by
Traceback (most recent call last):
File "/Users/carl/miniconda3/envs/env0/lib/python3.7/site-packages/PIL/JpegImagePlugin.py", line 620, in _save
rawmode = RAWMODE[im.mode]
KeyError: 'RGBA'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "example.py", line 14, in <module>
example()
File "example.py", line 12, in example
result.save('test1.jpg','JPEG')
File "/Users/carl/miniconda3/envs/env0/lib/python3.7/site-packages/PIL/Image.py", line 2007, in save
save_handler(self, fp, filename)
File "/Users/carl/miniconda3/envs/env0/lib/python3.7/site-packages/PIL/JpegImagePlugin.py", line 622, in _save
raise IOError("cannot write mode %s as JPEG" % im.mode)
OSError: cannot write mode RGBA as JPEG
The image is still RGBA after the convert to RGB function.
What am I doing wrong?
You missed to assign the output to result. Change this code below
old:
result.convert('RGB')
new:
result = result.convert('RGB')

FileNotFoundError: [WinError 2] | Errors reading text from image with Python, OpenCV and OCR

I'm having issues with this example code of how to read text from images using Python, OpenCV and OCR.
This code was built with python 2.7, and I'm using python 3.6 so maybe I'm missing some changes between these versions.
import cv2
import numpy as np
import pytesseract
from PIL import Image
src_path = "C:/Users/crist/Desktop/borrar/lectura/"
def get_string(img_path):
# Read image with opencv
img = cv2.imread(img_path)
# Convert to gray
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Apply dilation and erosion to remove some noise
kernel = np.ones((1, 1), np.uint8)
img = cv2.dilate(img, kernel, iterations=1)
img = cv2.erode(img, kernel, iterations=1)
# Write image after removed noise
cv2.imwrite(src_path + "removed_noise.png", img)
# Apply threshold to get image with only black and white
#img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 2)
# Write the image after apply opencv to do some ...
cv2.imwrite(src_path + "thres.png", img)
# Recognize text with tesseract for python
result = pytesseract.image_to_string(Image.open(src_path + "thres.png"))
#os.remove(temp)
return result
print ('--- Start recognize text from image ---')
print (get_string(src_path + "2.png"))
print ("------ Done -------")
Errors:
--- Start recognize text from image ---
Traceback (most recent call last):
File "C:/Users/crist/PycharmProjects/LectorTexto/lectorCapcha.py", line 40, in <module>
print (get_string(src_path + "2.png"))
File "C:/Users/crist/PycharmProjects/LectorTexto/lectorCapcha.py", line 31, in get_string
result = pytesseract.image_to_string(Image.open(src_path + "thres.png"))
File "C:\Users\crist\AppData\Local\Programs\Python\Python36\lib\site-packages\pytesseract\pytesseract.py", line 122, in image_to_string
config=config)
File "C:\Users\crist\AppData\Local\Programs\Python\Python36\lib\site-packages\pytesseract\pytesseract.py", line 46, in run_tesseract
proc = subprocess.Popen(command, stderr=subprocess.PIPE)
File "C:\Users\crist\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 707, in __init__
restore_signals, start_new_session)
File "C:\Users\crist\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 992, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] El sistema no puede encontrar el archivo especificado
Process finished with exit code 1
Import all the followings->>>>>>>
import cv2
import numpy as np
import pytesseract
import imutils
from PIL import Image
from pytesseract import image_to_string

python error on barcode generation

I am using python 2.7 and pyBarcode 0.7 in Windows and I am trying to generate barcode as png image by using following sample code (available in pyBarcode webpage)
>>> import barcode
>>> barcode.PROVIDED_BARCODES
[u'code39', u'ean', u'ean13', u'ean8', u'gs1', u'gtin', u'isbn', u'isbn10',
u'isbn13', u'issn', u'jan', u'pzn', u'upc', u'upca']
>>> EAN = barcode.get_barcode_class('ean13')
>>> EAN
<class 'barcode.ean.EuropeanArticleNumber13'>
>>> ean = EAN(u'5901234123457')
>>> ean
<barcode.ean.EuropeanArticleNumber13 object at 0x00BE98F0>
# Example with PNG
>>> from barcode.writer import ImageWriter
>>> ean = EAN(u'5901234123457', writer=ImageWriter())
>>> fullname = ean.save('ean13_barcode')
Last line generates following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\python27\lib\site-packages\barcode\base.py", line 68, in save
output = self.render(options)
File "c:\python27\lib\site-packages\barcode\ean.py", line 106, in render
return Barcode.render(self, options)
File "c:\python27\lib\site-packages\barcode\base.py", line 103, in render
raw = Barcode.raw = self.writer.render(code)
File "c:\python27\lib\site-packages\barcode\writer.py", line 188, in render
self._callbacks['paint_text'](xpos, ypos)
File "c:\python27\lib\site-packages\barcode\writer.py", line 280, in _paint_te
xt
font = ImageFont.truetype(FONT, self.font_size * 2)
File "c:\python27\lib\site-packages\PIL\ImageFont.py", line 218, in truetype
return FreeTypeFont(filename, size, index, encoding)
File "c:\python27\lib\site-packages\PIL\ImageFont.py", line 134, in __init__
self.font = core.getfont(file, size, index, encoding)
File "c:\python27\lib\site-packages\PIL\ImageFont.py", line 34, in __getattr__
raise ImportError("The _imagingft C module is not installed")
ImportError: The _imagingft C module is not installed
I retried by installing Pillow (but before that I removed PIL); I downloaded "Pillow-4.2.1-win32-py2_7.exe"
and I did also "pip install Pillow".
Now when I try to run
import barcode
I got:
File "barcode\codex.py", line 12, in <module>
from barcode.base import Barcode
File "barcode\base.py", line 9, in <module>
from barcode.writer import SVGWriter
File "barcode\writer.py", line 12, in <module>
import Image, ImageDraw, ImageFont
File "c:\python27\lib\site-packages\PIL\Image.py", line 27, in <module>
from . import VERSION, PILLOW_VERSION, _plugins
ValueError: Attempted relative import in non-package
What should I do ?
thanks

Pyglet and PIL: glError

I am wondering why I can get this error:
pyglet.lib.gl.GLExeption: invalid value
at: self.group = TextureGroup(image.load(TEXTURE_PATH).get_texture())
Imported libs:
import sys
import math
import random
import time
from collections import deque
from pyglet import image
from pyglet.gl import *
from pyglet.graphics import TextureGroup
from pyglet.window import key, mouse, Window
from PIL import Image
I'm using PIL for making the PNG:
print "Creating ", TEXTURE_PATH
images = map(Image.open, texture_path)
widths, heights = zip(*(i.size for i in images))
total_width = sum(widths)
max_height = max(heights)
new_im = Image.new('RGB', (total_width, max_height))
x_offset = 0
for im in images:
new_im.paste(im, (x_offset,0))
x_offset += im.size[0]
new_im.convert('RGB')
new_im.save(TEXTURE_PATH, "PNG")
And the 'texture_path`(lowercase) is here:
texture_path = ['res/textures/grass_top.png'] * 99
The full error message is:
Traceback (most recent call last):
File "D:\pythoncode\pyglet\minecraft_remake.py", line 955, in <module>
main()
File "D:\pythoncode\pyglet\minecraft_remake.py", line 948, in main
window = Window(width = 640, height = 480, caption="Minecraft 3d!", resizable=True)
File "D:\pythoncode\pyglet\minecraft_remake.py", line 554, in __init__
self.model = Model()
File "D:\pythoncode\pyglet\minecraft_remake.py", line 198, in __init__
self.group = TextureGroup(image.load(TEXTURE_PATH).get_texture())
File "C:\Python27\lib\site-packages\pyglet\image\__init__.py", line 818, in get_texture
force_rectangle)
File "C:\Python27\lib\site-packages\pyglet\image\__init__.py", line 803, in create_texture
rectangle, force_rectangle)
File "C:\Python27\lib\site-packages\pyglet\image\__init__.py", line 1514, in create
blank)
File "C:\Python27\lib\site-packages\pyglet\gl\lib.py", line 104, in errcheck
raise GLException(msg)
GLException: invalid value
I found the problem, but didn't know how to fix it, the problem are in the PNG making.
When I replace the textures.png with another picture, it's working
but when I make one with PIL, it doesn't work.
Solved: the problem is in my .PNG Editor, i just make the image manually and it works!
im using Graphics Gale Free edition to edit and it will work.
i think the problem is in the PIL itself. Or The pyglet doesnt load PIL config PNG
P.s it may be because color configuration

How do I use reportlab's drawImage with an image url?

When I try the following:
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen.canvas import Canvas
import urllib
import StringIO
import PIL.Image
image_file = urllib.urlopen('https://www.google.com/images/srpr/logo11w.png')
image_string = StringIO.StringIO(image_file.read())
logo = PIL.Image.open(image_string)
canvas = Canvas('output.pdf', pagesize=letter)
canvas.drawImage(logo, 10, 10)
canvas.showPage()
canvas.save()
I get this error:
Traceback (most recent call last):
File "imagefromurl.py", line 12, in <module>
canvas.drawImage(logo, 10, 10)
File "/usr/lib/python2.7/dist-packages/reportlab/pdfgen/canvas.py", line 857, in drawImage
imgObj = pdfdoc.PDFImageXObject(name, image, mask=mask)
File "/usr/lib/python2.7/dist-packages/reportlab/pdfbase/pdfdoc.py", line 2090, in __init__
ext = string.lower(os.path.splitext(source)[1])
File "/usr/lib/python2.7/posixpath.py", line 96, in splitext
return genericpath._splitext(p, sep, altsep, extsep)
File "/usr/lib/python2.7/genericpath.py", line 91, in _splitext
sepIndex = p.rfind(sep)
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 515, in __getattr__
raise AttributeError(name)
Reportlab is version 2.5.
I was doing it the hard way. This works (also added the necessary mask to avoid transparent becoming black):
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen.canvas import Canvas
from reportlab.lib.utils import ImageReader
logo = ImageReader('https://www.google.com/images/srpr/logo11w.png')
canvas = Canvas('output.pdf', pagesize=letter)
canvas.drawImage(logo, 10, 10, mask='auto')
canvas.showPage()
canvas.save()
Though the hard way would have allowed me to detect a failure to fetch the image url and handle it (e.g. substituting a local image), and this doesn't.

Categories