python 用turtle自动画图

1 篇文章 0 订阅
1 篇文章 1 订阅

你还在用turtle一笔一笔的画图吗?这篇文章主要是教你用python的turtle库自动画图,就是导入一张彩色或者灰色图片,然后用程序自动画图,全程自动,只需导入你想画的图就ok了,效果如下所示:
备注:在本文最后有该代码下载链接,如有需要请自行下载
在这里插入图片描述

海龟画图python

下面是代码:
导入模块

import turtle
import cv2 as cv
import numpy as np

读取图片,并设置相关参数

path=input('请输入图片路径')
src=cv.imread(path)
#print(src.shape)
cv.imshow('s1',src)
width=src.shape[1]
hight=src.shape[0]
print(width,hight)
turtle.setup(width+15,hight+15)
turtle.bgcolor(0,0,0)
turtle.pencolor(1,1,1)

用一个函数将图片左上角设置成坐标原点(0,0)

def y(x,y):
    x=x-1/2*width
    y=-(y-1/2*hight)
    return x,y

将图片转成灰度图并进行二值化

gray=cv.cvtColor(src,cv.COLOR_BGR2GRAY)
ret,image=cv.threshold(gray,0,255,cv.THRESH_OTSU)

使用opencv找轮廓

"""#找轮廓"""
counters,re=cv.findContours(image,cv.RETR_TREE,cv.CHAIN_APPROX_NONE)
print('轮廓个数:',len(counters))

然后就是便利轮廓进行画图

for i,con in enumerate(counters):
   
    area=cv.contourArea(con)

    con=np.reshape(con,(con.shape[0],2))

    turtle.goto(y(con[0,0],con[0,1]))
    turtle.pendown()


    biao_x1=np.argmin(con[:,0])
    x1=con[biao_x1,0]
    y1=con[biao_x1, 1]
    # print('x1,y1=',x1,y1)
  

    biao_x2=np.argmax(con[:,0])
    x2=con[biao_x2,0]
    y2=con[biao_x2,1]
    # print('x2,y2=', x2, y2)
 
    biao_y3=np.argmin(con[:,1])
    x3 = con[biao_y3, 0]
    y3=con[biao_y3,1]
    # print('x3,y3=', x3, y3)
    #下边坐标
    biao_y4=np.argmin(con[:,1])
    x4 = con[biao_y4, 0]
    y4=con[biao_y4,1]
    # print('x4,y4=', x4, y4)


    x1=x1
    #right
    x2=x2
    #up
    y3=y3
    #bottom
    y4=y4
    print('x1,y1=', x1, y1)
    print('x2,y2=', x2, y2)
    print('x3,y3=', x3, y3)
    print('x4,y4=', x4, y4)
    if x1<width and x2>=0 and y3<hight and y4>=0:
        a1=image[y1, x1]/255

        a2=image[y2,x2]/255

        a3=image[y3,x3]/255

        a4=image[y4,x4]/255
    else:a1=a2=a3=a4=0

    a=a1+a2+a3+a4
    
    turtle.begin_fill()
  
    if a>5:
        turtle.fillcolor(1,1,1)
    elif a<=5:
        turtle.fillcolor(0,0,0)
    #画图
    for shu,c in enumerate(con):
        turtle.goto(y(c[0],c[1]))
    turtle.goto(y(con[0, 0], con[0, 1]))
    turtle.end_fill()
    turtle.penup()

turtle.mainloop()

项目代码下载链接:项目下载链接

  • 9
    点赞
  • 71
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值