python - 检测图像中的文本位置并在 Python 中裁剪它

标签 python python-3.x image-processing python-imaging-library crop

我有这张图 Text in an image

我想检测该文本位置,并裁剪仅聚焦于该文本的图像。

这是我的代码:

from PIL import Image 
# Opens a image in RGB mode 
im = Image.open(r"image.jpg") 
# Size of the image in pixels (size of orginal image) 
# (This is not mandatory) 
width, height = im.size 
print(im.size)
# Setting the points for cropped image 
left = 5
top = height / 4
right = 164
bottom = 3 * height / 4
# Cropped image of above dimension 
# (It will not change orginal image) 
im1 = im.crop((left, top, right, bottom)) 
# Shows the image in image viewer 
im1.save("new.jpg")

这段代码工作正常,但图像中文本的位置不是静态的。 我希望代码自动检测文本的位置然后裁剪它。

最佳答案

您可以使用getbbox()来获取边界框:

image=Image.open('text.jpg') 
x1,y1,x2,y2=image.getbbox() 
print(x1,y1,x2,y2)   

输出

16 192 208 216

enter image description here

关于python - 检测图像中的文本位置并在 Python 中裁剪它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58048848/

相关文章:

python - 在Paramiko中的Windows SSH服务器上执行命令(pg_dump)之前设置环境变量(PGPASSWORD)

python - 在其他列表项中查找列表项的列表索引

python - 如何在OpenCV中检测数独网格板

python - 在 Django 中过滤

python - 一次随机将 Pandas 数据框分成几组以进行 x 折交叉验证

python - 动态添加字段到数据类对象

arrays - 将数组尽可能均匀地划分为子数组以进行核心映射

python - 如何提取图像中的绿色对象?

c++ - Python:将 unicode 字符串传递给 C++ 模块

python - 如何修复Python中的 "<string> DeprecationWarning: invalid escape sequence"?