用tkinter画线

问题描述 投票:0回答:1

我正在开发一个项目,要求我在图像上显示一个网格,但是我的代码一直出错,说'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()`
python python-3.x tkinter python-imaging-library cv2
1个回答
1
投票

我不认为你需要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步进网格。

© www.soinside.com 2019 - 2024. All rights reserved.