用 tkinter 画线

Drawing lines with tkinter

我正在做一个需要我在图像上显示网格的项目,但我的代码一直出错说 'numpy.ndarray' 对象没有属性 'load'。错误发生在 draw = ImageDraw.Draw(cv_img) 行。为什么会这样? `

import Tkinter
import cv2
from PIL import Image, ImageTk, ImageDraw
# Creates window
window = Tkinter.Tk()

# Load an image using OpenCV
cv_img = cv2.imread("P:\OneSky\United States.png", cv2.COLOR_BGR2RGB)
window.title("United States Map")

# Get the image dimensions (OpenCV stores image data as NumPy ndarray)
height, width, no_channels = cv_img.shape

# Create a canvas that can fit the above image
canvas = Tkinter.Canvas(window, width = width, height = height)
canvas.pack()

# Use PIL (Pillow) to convert the NumPy ndarray to a PhotoImage
photo = ImageTk.PhotoImage(image = Image.fromarray(cv_img))

# Add a PhotoImage to the Canvas
canvas.create_image(0, 0, image=photo, anchor=Tkinter.NW)

# Draws lines on map
draw = ImageDraw.Draw(cv_img)
x = cv_img.width/2
y_start = 0
y_end = cv_img.height
line = ((x,y_start), (x, y_end))
draw.line(line, fill=128)
del draw

# Run the window loop
window.mainloop()`

我认为你不需要 opencv,试试这样的东西:

from PIL import Image, ImageDraw, ImageTk
import tkinter as tk

def main():
    root = tk.Tk()
    root.title("United States Map")
    steps = 25
    img = Image.open('P:\OneSky\United States.png').convert('RGB')

    draw = ImageDraw.Draw(img)
    y_start = 0
    y_end = img.height
    step_size = int(img.width / steps)

    for x in range(0, img.width, step_size):
        line = ((x, y_start), (x, y_end))
        draw.line(line, fill=128)

    x_start = 0
    x_end = img.width

    for y in range(0, img.height, step_size):
        line = ((x_start, y), (x_end, y))
        draw.line(line, fill=128)

    del draw
    display = ImageTk.PhotoImage(img)
    label = tk.Label(root, image=display)
    label.pack()
    root.mainloop()


if __name__ == '__main__':
    main()

我从 here.

得到了如何步进网格的想法