python - 我需要解释的 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')
如果有人可以向我解释,那就太好了。谢谢!
解决方案
我将把上面的片段分成几部分并逐个解释。
第一个块是进口。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')
推荐阅读
- javascript - 当视频的当前时间大于某个值时执行函数
- docker - GOOGLE_APPLICATION_CREDENTIALS 在 Cloud Run Container 中未定义
- excel - VB.NET - 删除 Activecell 的“命名范围”
- excel - 将“Control + A”插入文本框
- git - GitHub,但大文件转到 Google Drive
- python-xarray - 如何在 xarray 的后端添加 fsspec.open_local
- android - Firestore 全文搜索 Android
- reactjs - 通过 redux-saga 调度操作时,React 应用程序冻结
- python - 是否有命令在同一驱动器上的 unRAID 共享之间移动文件指针?
- java - Payara Micro忽略persistence.xml中的连接url