# 点转图像测试程序,本程序是为在python海龟绘图中使用洪水填充而作的一个中间研究程序

### 点转图像测试程序,本程序是为在python海龟绘图中使用洪水填充而作的一个中间研究程序

```"""
点转图像测试程序,本程序是为在python海龟绘图中使用洪水填充而作的一个中间研究程序,作者李兴球.
"""
import cv2
import turtle
import numpy as np

def convert_turtle_xy(pos,w,h,img_w,img_h):
"""pos是以左上角为原点,向右为正x,向下为正y的坐标,函数把它转换成turtle坐标"""
x,y = pos
x = x - img_w//2
y = -y+ img_h//2
return x,y

def points2image(points):
"""坐标点转换为灰图像,x->,y向下为正"""
min_x = min([x for x,y in points])
max_x = max([x for x,y in points])
min_y = min([y for x,y in points])
max_y = max([y for x,y in points])
left,top = min_x,min_y
width = max_x - min_x +1
height = max_y - min_y +1
image = [[255 for i in range(width)] for j in range(height)]
new_points = [(x-left,y-top) for x,y in points]
#print('new_points=',new_points)
#for row in image:
#    print(row)
for i in range(height):
for j in range(width):
if (j,i) in new_points:
image[i][j] = 0
return image

# 这些坐标点是以左上角为原点的,(x向右为正,y轴向下为正)
A = (10,5);B=(10,200);C=(150,150);D=(200,100);E=(300,300);F=(330,330)
ps = [A,B,C,D,E,F]
img = points2image(ps)
gray = np.array(img,dtype='uint8')
print(gray)
img_height,img_width = gray.shape[0:]    # 高度、宽度

ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
print(gray)
# 提取轮廓
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

w,h = 800,900
turtle.setup(w,h)
turtle.penup()
turtle.speed(0)
turtle.delay(0)
for item in contours:
cors = [convert_turtle_xy(tuple(lis[0]),w,h,img_width,img_height) for lis in item]
cors.append(convert_turtle_xy(tuple(item[0][0]),w,h,img_width,img_height))
for x,y in cors:
turtle.goto(x,y);turtle.dot()
if not turtle.isdown():turtle.down()
turtle.penup()

```