当前位置:   article > 正文

python 用turtle自动画图_python自动绘图

python自动绘图

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

海龟画图python

下面是代码:
导入模块

import turtle
import cv2 as cv
import numpy as np
  • 1
  • 2
  • 3

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

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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

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

def y(x,y):
    x=x-1/2*width
    y=-(y-1/2*hight)
    return x,y
  • 1
  • 2
  • 3
  • 4
'
运行

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

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

使用opencv找轮廓

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

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

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()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/874205
推荐阅读
相关标签
  

闽ICP备14008679号