Ошибка Python в библиотеке OpenCV
Помогите пожалуйста. Столкнулся с ошибкой
Traceback (most recent call last):
File "C:\Users\Hp1\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:\Users\Hp1\PycharmProjects\untitled14\main.py", line 242, in convert
ArtAscii().run()
File "C:\Users\Hp1\PycharmProjects\untitled14\main.py", line 18, in __init__
self.image = self.get_image()
File "C:\Users\Hp1\PycharmProjects\untitled14\main.py", line 39, in get_image
gray_image = cv2.cvtColor(transposed_image, cv2.COLOR_BGR2GRAY)
cv2.error: OpenCV(4.4.0) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-tts2sm8m\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'
Я разрабатываю конвертор в ASCII и другую графику. Код:
import pygame as pg
import numpy as np
import pygame.gfxdraw
import cv2
from tkinter.filedialog import *
from tkinter import messagebox
mode = 0
filename = ''
filename2 = ''
class ArtAscii:
global filename, filename2
def __init__(self, path=filename, font_size=12):
pg.init()
self.path = path
self.image = self.get_image()
self.RES = self.WIDTH, self.HEIGHT = self.image.shape[0], self.image.shape[1]
self.surface = pg.display.set_mode(self.RES)
self.clock = pg.time.Clock()
self.ASCII_CHARS = ' .",:;!~+-xmo*#W&8@'
self.ASCII_COEFF = 255 // (len(self.ASCII_CHARS) - 1)
self.font = pg.font.SysFont('Courier', font_size, bold=True)
self.CHAR_STEP = int(font_size * 0.6)
self.RENDERED_ASCII_CHARS = [self.font.render(char, False, 'white') for char in self.ASCII_CHARS]
def draw_ascii_image(self):
char_indices = self.image // self.ASCII_COEFF
for x in range(0, self.WIDTH, self.CHAR_STEP):
for y in range(0, self.HEIGHT, self.CHAR_STEP):
char_index = char_indices[x, y]
if char_index:
self.surface.blit(self.RENDERED_ASCII_CHARS[char_index], (x, y))
def get_image(self):
self.cv2_image = cv2.imread(self.path)
transposed_image = cv2.transpose(self.cv2_image)
gray_image = cv2.cvtColor(transposed_image, cv2.COLOR_BGR2GRAY)
return gray_image
def draw_cv2_image(self):
resized_cv2_image = cv2.resize(self.cv2_image, (self.WIDTH // 2, self.HEIGHT // 2), interpolation=cv2.INTER_AREA)
cv2.imshow('img', resized_cv2_image)
def draw(self):
self.surface.fill('black')
self.draw_ascii_image()
self.draw_cv2_image()
def save_image(self):
pygame_image = pg.surfarray.array3d(self.surface)
cv2_img = cv2.transpose(pygame_image)
cv2.imwrite(filename2, cv2_img)
def run(self):
while True:
for i in pg.event.get():
if i.type == pg.QUIT:
exit()
elif i.type == pg.KEYDOWN:
if i.key == pg.K_s:
self.save_image()
self.draw()
pg.display.set_caption(str(self.clock.get_fps()))
pg.display.flip()
self.clock.tick()
class ArtAsciiColor:
global filename, filename2
def __init__(self, path=filename, font_size=12, color_lvl=8):
pg.init()
self.path = path
self.COLOR_LVL = color_lvl
self.image, self.gray_image = self.get_image()
self.RES = self.WIDTH, self.HEIGHT = self.image.shape[0], self.image.shape[1]
self.surface = pg.display.set_mode(self.RES)
self.clock = pg.time.Clock()
self.ASCII_CHARS = ' ixzao*MW&8%B@$'
self.ASCII_COEFF = 255 // (len(self.ASCII_CHARS) - 1)
self.font = pg.font.SysFont('Courier', font_size, bold=True)
self.CHAR_STEP = int(font_size * 0.6)
self.PALETTE, self.COLOR_COEFF = self.create_palette()
def draw_ascii_image(self):
char_indices = self.gray_image // self.ASCII_COEFF
color_indices = self.image // self.COLOR_COEFF
for x in range(0, self.WIDTH, self.CHAR_STEP):
for y in range(0, self.HEIGHT, self.CHAR_STEP):
char_index = char_indices[x, y]
if char_index:
char = self.ASCII_CHARS[char_index]
color = tuple(color_indices[x, y])
self.surface.blit(self.PALETTE[char][color], (x, y))
def create_palette(self):
colors, colors_coeff = np.linspace(0, 255, num=self.COLOR_LVL, dtype=int, retstep=True)
color_palette = [np.array([r, g, b]) for r in colors for g in colors for b in colors]
palette = dict.fromkeys(self.ASCII_CHARS, None)
colors_coeff = int(colors_coeff)
for char in palette:
char_palette = {}
for color in color_palette:
color_key = tuple(color // colors_coeff)
char_palette[color_key] = self.font.render(char, False, tuple(color))
palette[char] = char_palette
return palette, colors_coeff
def get_image(self):
self.cv2_image = cv2.imread(self.path)
transposed_image = cv2.transpose(self.cv2_image)
image = cv2.cvtColor(transposed_image, cv2.COLOR_BGR2RGB)
gray_image = cv2.cvtColor(transposed_image, cv2.COLOR_BGR2GRAY)
return image, gray_image
def draw_cv2_image(self):
resized_cv2_image = cv2.resize(self.cv2_image, (self.WIDTH // 2, self.HEIGHT // 2), interpolation=cv2.INTER_AREA)
cv2.imshow('img', resized_cv2_image)
def draw(self):
self.surface.fill('black')
self.draw_ascii_image()
self.draw_cv2_image()
def save_image(self):
pygame_image = pg.surfarray.array3d(self.surface)
cv2_img = cv2.transpose(pygame_image)
cv2.imwrite(filename2, cv2_img)
def run(self):
while True:
for i in pg.event.get():
if i.type == pg.QUIT:
exit()
elif i.type == pg.KEYDOWN:
if i.key == pg.K_s:
self.save_image()
self.draw()
pg.display.set_caption(str(self.clock.get_fps()))
pg.display.flip()
self.clock.tick()
class ArtPixel:
global filename, filename2
def __init__(self, path=filename, pixel_size=7, color_lvl=8):
pg.init()
self.path = path
self.PIXEL_SIZE = pixel_size
self.COLOR_LVL = color_lvl
self.image = self.get_image()
self.RES = self.WIDTH, self.HEIGHT = self.image.shape[0], self.image.shape[1]
self.surface = pg.display.set_mode(self.RES)
self.clock = pg.time.Clock()
self.PALETTE, self.COLOR_COEFF = self.create_palette()
def draw_ascii_image(self):
color_indices = self.image // self.COLOR_COEFF
for x in range(0, self.WIDTH, self.PIXEL_SIZE):
for y in range(0, self.HEIGHT, self.PIXEL_SIZE):
color_key = tuple(color_indices[x, y])
if sum(color_key):
color = self.PALETTE[color_key]
pygame.gfxdraw.box(self.surface, (x, y, self.PIXEL_SIZE, self.PIXEL_SIZE), color)
def create_palette(self):
colors, colors_coeff = np.linspace(0, 255, num=self.COLOR_LVL, dtype=int, retstep=True)
color_palette = [np.array([r, g, b]) for r in colors for g in colors for b in colors]
palette = {}
colors_coeff = int(colors_coeff)
for color in color_palette:
color_key = tuple(color // colors_coeff)
palette[color_key] = color
return palette, colors_coeff
def get_image(self):
self.cv2_image = cv2.imread(self.path)
transposed_image = cv2.transpose(self.cv2_image)
image = cv2.cvtColor(transposed_image, cv2.COLOR_BGR2RGB)
return image
def draw_cv2_image(self):
resized_cv2_image = cv2.resize(self.cv2_image, (self.WIDTH // 2, self.HEIGHT // 2), interpolation=cv2.INTER_AREA)
cv2.imshow('img', resized_cv2_image)
def draw(self):
self.surface.fill('black')
self.draw_ascii_image()
self.draw_cv2_image()
def save_image(self):
pygame_image = pg.surfarray.array3d(self.surface)
cv2_img = cv2.transpose(pygame_image)
cv2.imwrite(filename2, cv2_img)
def run(self):
while True:
for i in pg.event.get():
if i.type == pg.QUIT:
exit()
elif i.type == pg.KEYDOWN:
if i.key == pg.K_s:
self.save_image()
self.draw()
pg.display.set_caption(str(self.clock.get_fps()))
pg.display.flip()
self.clock.tick()
def image():
global filename
filename = askopenfilename(filetypes=[("Картинки", "*.jpg *.png")])
lbl.configure(text=filename)
def image_save():
global filename2
filename2 = askdirectory()
lbl1.configure(text=filename2)
def mode_rad1():
global mode
mode = 1
def mode_rad2():
global mode
mode = 2
def mode_rad3():
global mode
mode = 3
def convert():
if not filename:
messagebox.showerror('ОШИБКА 0000', 'Выбери картинку')
elif not filename2:
messagebox.showerror('ОШИБКА 0000', 'Выбери куда сохранить')
elif mode == 0:
messagebox.showerror('ОШИБКА 0000', 'Выбери режим')
else:
if mode == 1:
ArtAscii().run()
if mode == 2:
ArtAsciiColor().run()
if mode == 3:
ArtPixel().run()
if __name__ == '__main__':
window = Tk()
window.title("Конвертор")
window.geometry('250x150')
window.resizable(width=False, height=False)
lbl = Label(window, text="Выберите картинку")
lbl.place(x=60, y=15)
btn1 = Button(text="...", padx="4", pady="3", font="10", command=image)
btn1.place(x=200, y=10)
lbl1 = Label(window, text="Куда сохранить при нажатии S")
lbl1.place(x=25, y=50)
btn2 = Button(text="...", padx="4", pady="3", font="10", command=image_save)
btn2.place(x=200, y=45)
rad1 = Radiobutton(window, text='ASCII', value=1, command=mode_rad1)
rad2 = Radiobutton(window, text='ASCII COLOR', value=2, command=mode_rad2)
rad3 = Radiobutton(window, text='PIXEL ART', value=3, command=mode_rad3)
rad1.place(x=10, y=80)
rad2.place(x=60, y=80)
rad3.place(x=155, y=80)
btn3 = Button(text="КОНВЕРТИРОВАТЬ", padx="4", pady="3", font="10", command=convert)
btn3.place(x=40, y=110)
window.mainloop()
Заранее большое спасибо
Ответы (1 шт):
Автор решения: Ярослав Образцов
→ Ссылка
Я понял в чем ошибка когда я через tkinter получал картинку то слеши были такими / а что бы OpenCV нашел картинку слеши должны быть такими \