如何使用代码删除水印来获得与输出图像相同的名称?

2024-09-28 23:06:01 发布

您现在位置:Python中文网/ 问答频道 /正文

这是一个从图像中去除水印的代码,但是我在一些图像中有一个简单的问题,就是输出图像的名称在某些图像中缺少一个数字。代码如下:

#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。有人能帮忙吗?在


Tags: in图像名称imgforifosrange
1条回答
网友
1楼 · 发布于 2024-09-28 23:06:01
targetFile[0:targetFile.rfind('.')]

这就是问题所在。您试图切掉文件名最右边句点之后的所有内容,但是如果文件名没有句点,rfind返回{},并切掉最后一个字母。更简单的例子:

^{pr2}$

尝试使用os.path.splitext而不是自己切片字符串。它的存在正是为了这个目的。在

^{3}$

使用os.path.join而不是自己连接目录名也是一个好主意。你永远不知道什么时候你的代码会在一个对分隔符很挑剔的操作系统上运行。在

rgb_im.save(os.path.join(outputDir, os.path.splitext(targetFile)[0] + outputFormat))

相关问题 更多 >