这是一个从图像中去除水印的代码,但是我在一些图像中有一个简单的问题,就是输出图像的名称在某些图像中缺少一个数字。代码如下:
#coding:utf-8
import os
import os.path
from PIL import Image
outputFormat = '.png'
def hasBlackAround(x, y, distance, img):
w, h = img.size
startX = 0 if x - distance < 0 else x - distance
startY = 0 if y - distance < 0 else y - distance
endX = w - 1 if x + distance > w - 1 else x + distance
endY = h - 1 if y + distance > h - 1 else y + distance
hasBlackAround = False
for j in range(startX, endX):
for k in range(startY, endY):
r, g, b = img.getpixel((j, k))
if r < 130 and g < 130 and b < 130:
return True
return False
currentPath = os.getcwd()
fileList = os.listdir(currentPath)
for file in fileList:
if(os.path.isdir(file)):
targetFiles = os.listdir(file)
outputDir = file + '/output/'
if not os.path.isdir(outputDir):
os.makedirs(outputDir)
for targetFile in targetFiles:
try:
img = Image.open(file + '/' + targetFile)
w, h = img.size
rgb_im = img.convert('RGB')
for x in range(0, w - 1):
for y in range(0, h - 1):
if not hasBlackAround(x, y, 1, rgb_im):
rgb_im.putpixel((x, y), (255, 255, 255))
rgb_im.save(outputDir + targetFile[0:targetFile.rfind('.')] + outputFormat)
except IOError:
print targetFile + ' is not a image file'
except Exception as e:
print e
print 'Done'
示例图像名称:11A087 输出图像名称:11A08.png
我需要输出为11A087.png。有人能帮忙吗?在
这就是问题所在。您试图切掉文件名最右边句点之后的所有内容,但是如果文件名没有句点,},并切掉最后一个字母。更简单的例子:
^{pr2}$rfind
返回{尝试使用
^{3}$os.path.splitext
而不是自己切片字符串。它的存在正是为了这个目的。在使用
os.path.join
而不是自己连接目录名也是一个好主意。你永远不知道什么时候你的代码会在一个对分隔符很挑剔的操作系统上运行。在相关问题 更多 >
编程相关推荐