首页 存档 技术 查看内容

Python pillow计算椭圆图形几何中心

2018-3-30 13:00 |来自: 互联网 436 0

摘要: 本文所用测试图像文件位于当前文件夹的testimages子文件夹中,并且图像以白色为背景。 from PIL import Image import os def searchLeft(width, height, im): #从左向右扫描 for w in range(width): #从下向上 ...


本文所用测试图像文件位于当前文件夹的testimages子文件夹中,并且图像以白色为背景。


from PIL import Image

import os


def searchLeft(width, height, im):

#从左向右扫描

for w in range(width):

#从下向上扫描

for h in range(height):

#获取图像指定位置的像素颜色

color = im.getpixel((w, h))

if color != (255, 255, 255):

#遇到并返回椭圆边界最左端的x坐标

return w



def searchRight(width, height, im):

#从右向左扫描

for w in range(width-1, -1, -1):

for h in range(height):

color = im.getpixel((w, h))

if color != (255, 255, 255):

#遇到并返回椭圆边界最右端的x坐标

return w

def searchTop(width, height, im):

for h in range(height-1, -1, -1):

for w in range(width):

color = im.getpixel((w,h))

if color != (255, 255, 255):

#遇到并返回椭圆边界最上端的y坐标

return h


def searchBottom(width, height, im):

for h in range(height):

for w in range(width):

color = im.getpixel((w,h))

if color != (255, 255, 255):

#遇到并返回椭圆边界最下端的y坐标

return h


#遍历指定文件夹中所有bmp图像文件,假设图像为白色背景,椭圆为其他任意颜色

images = [f for f in os.listdir('testimages') if f.endswith('.png')]

for f in images:

f = 'testimages\\' f

im = Image.open(f)

#获取图像大小

width, height = im.size

x0 = searchLeft(width, height, im)

x1 = searchRight(width, height, im)

y0 = searchBottom(width, height, im)

y1 = searchTop(width, height, im)

center = ((x0 x1)//2, (y0 y1)//2)


#把椭圆中心像素画成红色

im.putpixel(center, (255,0,0))

#保存为新图像文件

im.save(f[0:-4] '_center.webp')

im.close()


测试结果:

原始图像1

运行结果:

原始图像2:

运行结果:

声明:文章版权归原作者所有 部分文章转自互联网 如有侵权请联系 [邮箱地址] 删除

路过

雷人

握手

鲜花

鸡蛋

相关分类

返回顶部