过去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')
如果有人可以向我解释,那就太好了。 谢谢!
答案 0 :(得分:2)
我将上面的代码片段分成几部分,并分别进行解释。
第一个块是导入。 PIL
通常是通过安装Pillow
库来导入的。 textwrap
和pathlib
是Python Standard Library中包含的两个软件包。
#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')