使用Python中的“rich”库将网络摄像头优化为ASCII的问题

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

其代码是用Python编写的,如下

from PIL import Image
from rich.console import Console
from rich.text import Text
from cv2 import imwrite, VideoCapture
from os import system, name

# Function to map pixels to ASCII characters
def pixel_to_ascii(pixel, ascii_chars):
    return ascii_chars[pixel * len(ascii_chars) // 256]

# Function to convert image to colored ASCII
def image_to_ascii_with_color(image_path, new_width=100):
    ASCII_CHARS =  ["█"]

    # Open the image
    image = Image.open(image_path)

    # Resize the image maintaining the aspect ratio
    width, height = image.size
    aspect_ratio = height / width
    new_height = int(aspect_ratio * new_width * 0.4)
    image = image.resize((new_width, new_height))

    # Convert the image to grayscale
    gray_image = image.convert("L")

    # Get pixel data
    pixels = gray_image.getdata()
    color_pixels = image.getdata()

    # Create ASCII art
    ascii_str = "".join(pixel_to_ascii(p, ASCII_CHARS) for p in pixels)

    # Split ASCII string into lines
    lines = [ascii_str[i:i + new_width] for i in range(0, len(ascii_str), new_width)]

    # Print colored ASCII art using rich
    console = Console()
    for y, line in enumerate(lines):
        rich_text = Text()
        for x, char in enumerate(line):
            index = y * new_width + x
            if index < len(color_pixels):
                r, g, b = color_pixels[index]
                rich_text.append(char, style=f"rgb({r},{g},{b})")
        console.print(rich_text)

# Function to capture photo from webcam
def capture_photo(filename='1.jpg'):
    cap = VideoCapture(0)
    if not cap.isOpened():
        print("Error: Could not open webcam.")
        return False

    ret, frame = cap.read()
    cap.release()

    if not ret:
        print("Error: Could not read frame.")
        return False

    imwrite(filename, frame)
    return True

# Main function
def main():
    while True:
        if capture_photo():
            system('cls' if name == 'nt' else 'clear')
            image_to_ascii_with_color('image.jpg')

if __name__ == "__main__":
    main()

每当我运行它时,它都非常慢,有时开始滞后并在图像上产生伪影,使其看起来很糟糕。一开始它会工作得很好,但运行得越多,它就越滞后并导致工件。我所说的伪像是在画布上传播的错误颜色的像素。

我尝试使用 functools @cache 但没有找到优化它或消除工件的方法。我不知道问题是否可以解决,或者是否是丰富的图书馆的错,但如果有人可以提供帮助,那就太好了。另外,如果有人可以在他们的终端中测试工件,我们将不胜感激。请帮我弄清楚这个优化和“丰富”库的秘密。

python optimization ascii webcam rich
1个回答
0
投票

这对我来说没有伪影:

from PIL import Image
from rich.console import Console
from rich.text import Text
from cv2 import imwrite, VideoCapture
from os import system, name

# Function to map pixels to ASCII characters
def pixel_to_ascii(pixel, ascii_chars):
    return ascii_chars[pixel * len(ascii_chars) // 256]

# Function to convert image to colored ASCII
def image_to_ascii_with_color(image_path, new_width=100):
    global console
    ASCII_CHARS =  ["█"]

    # Open the image
    image = Image.open(image_path)

    # Resize the image maintaining the aspect ratio
    width, height = image.size
    aspect_ratio = height / width
    new_height = int(aspect_ratio * new_width * 0.4)
    image = image.resize((new_width, new_height))

    # Convert the image to grayscale
    gray_image = image.convert("L")

    # Get pixel data
    pixels = gray_image.getdata()
    color_pixels = image.getdata()

    # Create ASCII art
    ascii_str = "".join(pixel_to_ascii(p, ASCII_CHARS) for p in pixels)

    # Split ASCII string into lines
    lines = [ascii_str[i:i + new_width] for i in range(0, len(ascii_str), new_width)]

    for y, line in enumerate(lines):
        rich_text = Text()
        for x, char in enumerate(line):
            index = y * new_width + x
            if index < len(color_pixels):
                r, g, b = color_pixels[index]
                rich_text.append(char, style=f"rgb({r},{g},{b})")
        console.print(rich_text)
        

# Function to capture photo from webcam
def capture_photo(filename='1.jpg'):
    cap = VideoCapture(0)
    if not cap.isOpened():
        print("Error: Could not open webcam.")
        return False

    ret, frame = cap.read()
    cap.release()

    if not ret:
        print("Error: Could not read frame.")
        return False

    imwrite(filename, frame)
    return True

from time import perf_counter as T, sleep
maxTime = 20
frameRate = 5 # one frame per second
# console = Console()
# Create a console instance with force_terminal=True
target_dT = 1/frameRate
console = Console(force_terminal=True)

# Main function
def main():
    # Print colored ASCII art using rich
    sT=T()
    sT0=sT
    while True:
        if capture_photo():
            system('cls' if name == 'nt' else 'clear')
            image_to_ascii_with_color('1.jpg')
        else:
            exit(1)
        eT=T()
        if eT-sT  < target_dT :
            sleep(target_dT  - (eT-sT))
        sT=T()
        if eT-sT0 > maxTime:
            break   

if __name__ == "__main__":
    main()
#Whenever I run it it is very slow and sometimes starts to lag and make artifacts on the 
#image making it look horrible. It will work fine at the start but the more it runs the more 
# it lags and causes artifacts. The artifacts I'm talking about are miscolored pixels 
# spreading through the canvas.
#I have tried to use functools @cache and have not found a way to optimize it or get rid 
# of the artifacts. I don't know if the problem can be fixed or if it is the rich library's fault 
# but if someone could help that would be great. 
# Also if someone could test for the artifacts in their terminal it would be appreciated. 
# Please help me figure out this optimization and 'rich' library mystory.
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.