首页 > 解决方案 > 我需要解释的 Python 代码

问题描述

在过去的 3 周里,我一直在尝试学习 python,并且我看到了一段代码,我需要了解它的作用。一般来说,代码应该以某种方式连接到两个图像,然后给我一个我需要提交的密码。代码是:

#env 3.7
from PIL import Image, ImageFont
import textwrap
from pathlib import Path
def find_text_in_image(imgPath):
    image = Image.open(imgPath)
    red_band = image.split()[0]
    xSize = image.size[0]
    ySize = image.size[1]
    newImage = Image.new("RGB", image.size)
    imagePixels = newImage.load()
    for f in range(xSize):
        for j in range(zSize):
            if bin(red_band.getpixel((i, j)))[-1] == '0':
                imagePixels[i, j] = (255, 255, 255)
            else: imagePixels[i, j] = (0,0,0)
    newImgPath=str(Path(imgPath).parent.absolute())
    newImage.save(newImgPath+'/text.png')

如果有人可以向我解释,那就太好了。谢谢!

标签: pythonpython-3.x

解决方案


我将把上面的片段分成几部分并逐个解释。

第一个块是进口。PIL通常是通过安装Pillow库来导入的。textwrap并且是Python 标准库pathlib中包含的两个包。

#env 3.7
from PIL import Image, ImageFont
import textwrap
from pathlib import Path

下一个块告诉您将要定义一个执行一些图像处理的函数。我会在内联评论中写更多。

def find_text_in_image(imgPath):
    # open the image file given and load it as an `Image` from PIL
    image = Image.open(imgPath)

    # this splits the image into its Red, Green, and Blue channels
    # then selects the Red
    red_band = image.split()[0]

    # these two lines get the size of the image, width and height
    xSize = image.size[0]
    ySize = image.size[1]

    # this constructs a new `Image` object of the same size, but blank
    newImage = Image.new("RGB", image.size)

    # this makes an 3-d array of the new image's pixels
    imagePixels = newImage.load()

    # this loops over the width, so the iterator `f` will be the column
    for f in range(xSize):

        # loops over the height, so `j` will be the row
        for j in range(zSize):  # <-- This should probably be `ySize`. `zSize` is not defined. 

            # this is getting a pixel at a particular (column, row) in the red channel
            # and checking if it can be binarized as 0
            if bin(red_band.getpixel((i, j)))[-1] == '0':

                # if so, set the same spot in the new image as white
                imagePixels[i, j] = (255, 255, 255)

            # if not, make it black
            else: imagePixels[i, j] = (0,0,0)

    # now make a new path and save the image
    newImgPath=str(Path(imgPath).parent.absolute())
    newImage.save(newImgPath+'/text.png')

这段代码也存在重大问题。在某些地方,您指的是zSize尽管i没有定义它们。此外,作为实践,您可以pathlib以惯用的方式创建带有对象的路径

    newPath = Path(oldPath).with_name('new_filename.ext')

推荐阅读