我正在一个项目上,要求我在图像上显示网格,但是我的代码不断出错,说“ 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()`
答案 0 :(得分: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步进网格。