「图像处理」图像转字符画,在终端中用字符的形式显示摄像头画面。(python、opencv、rich)

算是一个无聊之举吧

不过在没有可视化桌面的情况下,设备连接了摄像头,怎样查看摄像头画面呢?这算是一种方案吧。

1、调用摄像头获取画面

参考之前的文章:https://blog.csdn.net/Raink_LH/article/details/111582308?spm=1001.2014.3001.5501

while循环获取当前画面,但不用显示(不调用cv2.imshow())

import os
import cv2
import time
from threading import Thread
from queue import Queue

class Camera:
    def __init__(self, device_id, frame_queue):
        self.device_id = device_id  # 摄像头id
        self.cam = cv2.VideoCapture(self.device_id)  # 获取摄像头
        self.frame_queue = frame_queue  # 帧队列
        self.is_running = False  # 状态标签
        self.fps = 0.0  # 实时帧率
        self._t_last = time.time() * 1000
        self._data = {} 
 
    def capture_queue(self):
        # 捕获图像
        self._t_last = time.time() * 1000
        while self.is_running and self.cam.isOpened():
            ret, frame = self.cam.read()
            if not ret:
                break
            if self.frame_queue.qsize() < 1: 
                # 当队列中的图像都被消耗完后,再压如新的图像              
                t  = time.time() * 1000 
                t_span = t - self._t_last                
                self.fps = int(1000.0 / t_span)
                self._data["image"] = frame.copy()
                self._data["fps"] = self.fps
                self.frame_queue.put(self._data)
                self._t_last = t
 
    def run(self):
        self.is_running = True
        self.thread_capture = Thread(target=self.capture_queue)
        self.thread_capture.start()
 
    def stop(self):
        self.is_running = False
        self.cam.release()

2、像素转字符

我这里选择用一些汉字来代替像素,首先考虑黑白情况(终端黑底白字,只可能黑白图像)。

把彩色图变成黑白图后,像素值在0~255区间,缩减到0~25的数值区间,并用26个汉字对应。

像素值越小,对应画面越暗,考虑到终端是黑色背景,就用越简单的字代替,值越大,对应的字越复杂。

我所挑选的汉字是:

pix_map = ["一", "二", "十", "了", "工", "口", 
           "仁", "日", "只", "长", "王", "甘", 
           "舟", "目", "自", "革", "固", "国", 
           "制", "冒", "筋", "最", "酶", "藏", "霾", "龘"]

接着,对每一帧的画面进行字符转换:

def detec_show(frame): 
    os.system('cls')    
    while flag_cam_run:
        if frame.qsize() > 0:
            data = frame.get()        
            image = cv2.resize(data["image"], (80, 60))
            image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
            str_img = ""
            for i in range(image.shape[0]):
                for j in range(image.shape[1]):
                    index = int(image[i][j] /10.0 + 0.5)
                    if index < 0: index = 0
                    if index > 25: index = 25
                    str_img += pix_map[index]
                str_img += "\n"
            print("------------------------------------")
            print(str_img)
            print("------------------------------------")
            frame_queue.task_done()
            os.system('cls') 
        if not flag_cam_run: 
            break

主函数代码:

if __name__ == "__main__":
    # 启动 获取摄像头画面的 线程
    frame_queue = Queue()
    cam = Camera(0, frame_queue)
    cam.run()
    flag_cam_run = True
    # 启动处理(显示)摄像头画面的线程
    thread_show = Thread(target=detec_show, args=(frame_queue,))
    thread_show.start()
    time.sleep(60)  # 运行1分钟后自动关闭
    cam.stop()
    flag_cam_run = False

在终端中运行,效果如下

3、加入颜色

现在很多终端也能显示颜色,借助一个python库:rich

修改每一帧的转换代码:

from rich.console import Console
from rich.text import Text

def detec_show(frame): 
    console = Console()    
    while flag_cam_run:
        if frame.qsize() > 0:
            data = frame.get()        
            image = cv2.resize(data["image"], (64, 48))
            image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
            text = Text("")
            for i in range(image.shape[0]):
                for j in range(image.shape[1]):
                    gray = 0.3*image[i][j][0] + 0.59*image[i][j][1] + 0.11*image[i][j][2]
                    index = int(gray /10.0 + 0.5)
                    if index < 0: index = 0
                    if index > 25: index = 25
                    style_ij="rgb({},{},{})".format(image[i][j][0], image[i][j][1], image[i][j][2])
                    text.append(pix_map[index], style=style_ij)
                text.append("\n")
            print("------------------------------------")
            console.print(text)     
            print("------------------------------------")
            frame_queue.task_done()
            time.sleep(0.5)  
            console.clear()
        if not flag_cam_run: 
            break

再次运行,效果如下:

因为要对每个字符渲染颜色,速度很受影像,所以图像缩放做了调整,从黑白的60x80,变成了48x64。

而且使用了rich.console 中的 Console,清屏操作前需要一点等待,否则就没有画面了。所以可能会慢一点。。。。


纯属娱乐,哪里可以优化的,请告诉我,多谢。

源码地址:https://github.com/RainkLH/Image_to_ASCII-Art

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值