Skip to content

Commit 802c46c

Browse files
Robert Sachunskyfinkf
authored andcommitted
ocrolib: ensure closing FDs after mkstemp and PIL.Image.open
1 parent b4a8e9f commit 802c46c

File tree

2 files changed

+11
-9
lines changed

2 files changed

+11
-9
lines changed

ocrd_cis/ocropy/common.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -402,6 +402,7 @@ def DSAVE(title,array, interactive=False):
402402
from matplotlib import cm
403403
from matplotlib import patches as mpatches
404404
from tempfile import mkstemp
405+
from os import close
405406
# set uniformly bright / maximally differentiating colors
406407
cmap = cm.rainbow # default viridis is too dark on low end
407408
# use black for bg (not in the cmap)
@@ -440,8 +441,9 @@ def on_press(event):
440441
plt.disconnect('key_press_event')
441442
return result
442443
else:
443-
_,fname = mkstemp(suffix=title+".png")
444+
fd, fname = mkstemp(suffix=title+".png")
444445
plt.imsave(fname,array,vmin=vmin,vmax=vmax,cmap=cmap)
446+
close(fd)
445447
LOG.debug('DSAVE %s', fname)
446448

447449
@checks(ABINARY2,NUMBER)

ocrd_cis/ocropy/ocrolib/common.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -165,8 +165,8 @@ def read_image_gray(fname,pageno=0):
165165
the range 0...1 (unsigned) or -1...1 (signed)."""
166166
if type(fname)==tuple: fname,pageno = fname
167167
assert pageno==0
168-
pil = PIL.Image.open(fname)
169-
a = pil2array(pil)
168+
with PIL.Image.open(fname) as pil:
169+
a = pil2array(pil)
170170
if a.dtype==dtype('uint8'):
171171
a = a/255.0
172172
if a.dtype==dtype('int8'):
@@ -202,8 +202,8 @@ def read_image_binary(fname,dtype='i',pageno=0):
202202
of the given dtype."""
203203
if type(fname)==tuple: fname,pageno = fname
204204
assert pageno==0
205-
pil = PIL.Image.open(fname)
206-
a = pil2array(pil)
205+
with PIL.Image.open(fname) as pil:
206+
a = pil2array(pil)
207207
if a.ndim==3: a = amax(a,axis=2)
208208
return array(a>0.5*(amin(a)+amax(a)),dtype)
209209

@@ -256,8 +256,8 @@ def make_seg_white(image):
256256
def read_line_segmentation(fname):
257257
"""Reads a line segmentation, that is an RGB image whose values
258258
encode the segmentation of a text line. Returns an int array."""
259-
pil = PIL.Image.open(fname)
260-
a = pil2array(pil)
259+
with PIL.Image.open(fname) as pil:
260+
a = pil2array(pil)
261261
assert a.dtype==dtype('B')
262262
assert a.ndim==3
263263
image = rgb2int(a)
@@ -276,8 +276,8 @@ def write_line_segmentation(fname,image):
276276
def read_page_segmentation(fname):
277277
"""Reads a page segmentation, that is an RGB image whose values
278278
encode the segmentation of a page. Returns an int array."""
279-
pil = PIL.Image.open(fname)
280-
a = pil2array(pil)
279+
with PIL.Image.open(fname) as pil:
280+
a = pil2array(pil)
281281
assert a.dtype==dtype('B')
282282
assert a.ndim==3
283283
segmentation = rgb2int(a)

0 commit comments

Comments
 (0)