前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python+pillow计算椭圆图形几何中心

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

作者头像
Python小屋屋主
发布2018-04-16 17:12:34
1.7K0
发布2018-04-16 17:12:34
举报
文章被收录于专栏:Python小屋Python小屋

本文所用测试图像文件位于当前文件夹的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.png')

im.close()

测试结果:

原始图像1

运行结果:

原始图像2:

运行结果:

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2017-04-30,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Python小屋 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档