Full Code of BEPb/image_to_ascii for AI

master 874ab21a88cb cached
12 files
28.8 KB
8.0k tokens
20 symbols
1 requests
Download .txt
Repository: BEPb/image_to_ascii
Branch: master
Commit: 874ab21a88cb
Files: 12
Total size: 28.8 KB

Directory structure:
gitextract_25iimfmq/

├── LICENSE
├── README.chinese.md
├── README.hindi.md
├── README.md
├── README.portuguese.md
├── README.ru.md
├── img_to_txt.py
├── img_to_txt_rus.py
├── requirements.txt
├── texts/
│   └── out.txt
├── video_to_txt.py
└── video_to_txt_rus.py

================================================
FILE CONTENTS
================================================

================================================
FILE: LICENSE
================================================
MIT License

Copyright (c) 2023 Andrej Marinchenko

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


================================================
FILE: README.chinese.md
================================================
<p>
  <img  src="https://img.shields.io/github/stars/BEPb/image_to_ascii" />
  <img src="https://img.shields.io/github/contributors/BEPb/image_to_ascii" />
  <img src="https://img.shields.io/github/last-commit/BEPb/image_to_ascii" />
  <img src="https://visitor-badge.laobi.icu/badge?page_id=BEPb.image_to_ascii" />
  <img src="https://img.shields.io/github/languages/count/BEPb/image_to_ascii" />
  <img src="https://img.shields.io/github/languages/top/BEPb/image_to_ascii" />

  <img src="https://img.shields.io/badge/license-MIT-blue.svg?color=f64152" />
  <img  src="https://img.shields.io/github/issues/BEPb/image_to_ascii" />
  <img  src="https://img.shields.io/github/issues-pr/BEPb/image_to_ascii" />
</p>


# 将图像转换为 .txt 文件
Read in other languages: [English](README.md), [हिन्दी](README.hindi.md), [Português](README.portuguese.md), [Русский](README.ru.md)

## 怎么运行的?

一切都很简单:你要么下载一个图片文件,要么在运行 python 脚本时指定它的链接,然后
输出你得到一个文本文件,你可以立即在命令行上查看它的外观
你转换的结果。

## 准备和使用机器人的程序

* 克隆存储库或从 github 下载存档或在命令行上使用以下命令

   ```commandline
   $ cmd
   $ git clone https://github.com/BEPb/image_to_ascii
   $ cd image_to_ascii
   ```

### 应用存储库
* 从文件安装依赖项,为此,在命令行中输入以下代码:

```shell
$ pip3 install -r requirements.txt
````

* 程序启动的一般形式:

```shell
$ python3 img_to_txt_rus.py [file/url] [size]
```

*参数:

```shell
[file/url]:本地文件路径或在线图片URL。
[size]:输出txt图片的字符宽度——整数,size越大图片越清晰。
```

### 例子
```shell
$ python3 img_to_txt.py https://i.postimg.cc/t4Cmn7wC/py.png
```
通过执行此命令,您将在当前“文本”文件夹中获得一个名为“out.txt”的文件,您将在控制台中看到该行的输出:

<img src="./pictures/py.png" alt="Bot logo" width="300" height="356.5">

<img src="./pictures/png.png" alt="Bot logo" width="600" height="600">


## 视频到文本转换器
原理类似,只是生成的文本文件不存在。

```commandline
cd C:\Users\root\PycharmProjects\image_to_ascii 
python video_to_txt.py animations\filin.gif 150
```

<img src="./animations/filin.gif" alt="Bot logo" width="800" height="600">

<img src="./animations/gif.gif" alt="Bot logo" width="800" height="600">



### License
[MIT licence](LICENSE)


================================================
FILE: README.hindi.md
================================================
<p>
  <img  src="https://img.shields.io/github/stars/BEPb/image_to_ascii" />
  <img src="https://img.shields.io/github/contributors/BEPb/image_to_ascii" />
  <img src="https://img.shields.io/github/last-commit/BEPb/image_to_ascii" />
  <img src="https://visitor-badge.laobi.icu/badge?page_id=BEPb.image_to_ascii" />
  <img src="https://img.shields.io/github/languages/count/BEPb/image_to_ascii" />
  <img src="https://img.shields.io/github/languages/top/BEPb/image_to_ascii" />

  <img src="https://img.shields.io/badge/license-MIT-blue.svg?color=f64152" />
  <img  src="https://img.shields.io/github/issues/BEPb/image_to_ascii" />
  <img  src="https://img.shields.io/github/issues-pr/BEPb/image_to_ascii" />
</p>


# एक छवि को एक .txt फ़ाइल में कनवर्ट करना
Read in other languages: [English](README.md), [Русский](README.ru.md), [中國人](README.chinese.md), [Português](README.portuguese.md)

## यह काम किस प्रकार करता है?

सब कुछ बहुत सरल है: आप या तो चित्र फ़ाइल डाउनलोड करते हैं या पायथन स्क्रिप्ट चलाते समय इसका लिंक निर्दिष्ट करते हैं, और
आउटपुट आपको एक टेक्स्ट फ़ाइल मिलती है, और आप तुरंत कमांड लाइन पर देख सकते हैं कि यह कैसा दिखेगा
आपके रूपांतरण का परिणाम।

## बॉट तैयार करने और उसके साथ काम करने की प्रक्रिया

* रिपॉजिटरी को क्लोन करें या जीथब से आर्काइव डाउनलोड करें या कमांड लाइन पर निम्न कमांड का उपयोग करें

   ```commandline
   $ cmd
   $ git clone https://github.com/BEPb/image_to_ascii
   $ cd image_to_ascii
   ```

### रिपॉजिटरी को लागू करना
* एक फ़ाइल से निर्भरताएँ स्थापित करें, इसके लिए कमांड लाइन में निम्न कोड दर्ज करें:

```shell
$ pip3 install -r requirements.txt
````

* प्रोग्राम लॉन्च का सामान्य रूप:

```shell
$ python3 img_to_txt_rus.py [file/url] [size]
```

* तर्क:

```shell
[file/url]: स्थानीय फ़ाइल पथ या ऑनलाइन छवि URL।
[size]: वर्णों में आउटपुट txt छवि की चौड़ाई - एक पूर्णांक, आकार जितना बड़ा होगा, चित्र उतना ही स्पष्ट होगा।
```

### उदाहरण
```shell
$ python3 img_to_txt.py https://i.postimg.cc/t4Cmn7wC/py.png
```
इस कमांड को क्रियान्वित करने पर, आपको वर्तमान 'टेक्स्ट' फोल्डर में `out.txt` नाम की एक फाइल मिलेगी और आप कंसोल में लाइन का आउटपुट देखेंगे:


<img src="./pictures/py.png" alt="Bot logo" width="300" height="356.5">

<img src="./pictures/png.png" alt="Bot logo" width="600" height="600">


## वीडियो से टेक्स्ट कन्वर्टर
सिद्धांत समान है, सिवाय इसके कि परिणामी पाठ फ़ाइल मौजूद नहीं है।

```commandline
cd C:\Users\root\PycharmProjects\image_to_ascii 
python video_to_txt.py animations\filin.gif 150
```

<img src="./animations/filin.gif" alt="Bot logo" width="800" height="600">

<img src="./animations/gif.gif" alt="Bot logo" width="800" height="600">



### License
[MIT licence](LICENSE)


================================================
FILE: README.md
================================================
<p>
  <img  src="https://img.shields.io/github/stars/BEPb/image_to_ascii" />
  <img src="https://img.shields.io/github/contributors/BEPb/image_to_ascii" />
  <img src="https://img.shields.io/github/last-commit/BEPb/image_to_ascii" />
  <img src="https://visitor-badge.laobi.icu/badge?page_id=BEPb.image_to_ascii" />
  <img src="https://img.shields.io/github/languages/count/BEPb/image_to_ascii" />
  <img src="https://img.shields.io/github/languages/top/BEPb/image_to_ascii" />

  <img src="https://img.shields.io/badge/license-MIT-blue.svg?color=f64152" />
  <img  src="https://img.shields.io/github/issues/BEPb/image_to_ascii" />
  <img  src="https://img.shields.io/github/issues-pr/BEPb/image_to_ascii" />
</p>


# Converting an image to a .txt file
Read in other languages: [Русский](README.ru.md), [हिन्दी](README.hindi.md), [中國人](README.chinese.md), [Português](README.portuguese.md)

## How it works?

Everything is very simple: you either download a picture file or specify its link when running a python script, and
output you get a text file, and you can immediately view on the command line how it will look
the result of your conversion.

## Procedure for preparing and working with the bot

* Clone the repository or download the archive from github or using the following commands on the command line

   ```commandline
   $ cmd
   $ git clone https://github.com/BEPb/image_to_ascii
   $ cd image_to_ascii
   ```

### Applying the repository
* Install dependencies from a file, for this, enter the following code in the command line:

```shell
$ pip3 install -r requirements.txt
````

* general form of program launch:

```shell
$ python3 img_to_txt_rus.py [file/url] [size]
```

* arguments:

```shell
[file/url]: Local file path or online image URL.
[size]: The width of the output txt image in characters - an integer, The larger the size, the clearer the picture.
```

### Example
```shell
$ python3 img_to_txt.py https://i.postimg.cc/t4Cmn7wC/py.png
```
By executing this command, you will get a file in the current 'texts' folder named `out.txt` and you will see the output of the line in the console:


<img src="./pictures/py.png" alt="Bot logo" width="300" height="356.5">

<img src="./pictures/png.png" alt="Bot logo" width="600" height="600">


## Video to Text Converter
The principle is similar, except that the resulting text file does not exist.

```commandline
cd C:\Users\root\PycharmProjects\image_to_ascii 
python video_to_txt.py animations\filin.gif 150
```

<img src="./animations/filin.gif" alt="Bot logo" width="800" height="600">

<img src="./animations/gif.gif" alt="Bot logo" width="800" height="600">



### License
[MIT licence](LICENSE)


================================================
FILE: README.portuguese.md
================================================
<p>
  <img  src="https://img.shields.io/github/stars/BEPb/image_to_ascii" />
  <img src="https://img.shields.io/github/contributors/BEPb/image_to_ascii" />
  <img src="https://img.shields.io/github/last-commit/BEPb/image_to_ascii" />
  <img src="https://visitor-badge.laobi.icu/badge?page_id=BEPb.image_to_ascii" />
  <img src="https://img.shields.io/github/languages/count/BEPb/image_to_ascii" />
  <img src="https://img.shields.io/github/languages/top/BEPb/image_to_ascii" />

  <img src="https://img.shields.io/badge/license-MIT-blue.svg?color=f64152" />
  <img  src="https://img.shields.io/github/issues/BEPb/image_to_ascii" />
  <img  src="https://img.shields.io/github/issues-pr/BEPb/image_to_ascii" />
</p>


# Convertendo uma imagem para um arquivo de texto
Leia em outros idiomas: [Русский](README.ru.md), [हिन्दी](README.hindi.md), [中國人](README.chinese.md), [English](README.md)

## Como funciona

Tudo é muito simples: você baixa um arquivo de imagem ou especifica seu link ao executar um script python e
saída, você obtém um arquivo de texto e pode visualizar imediatamente na linha de comando como ele ficará
o resultado da sua conversão.

## Processo para preparar e trabalhar com o bot

* Clone o repositório ou baixe o arquivo do GitHub ou use os seguintes comandos na linha de comando

   ```commandline
   $ cmd
   $ git clone https://github.com/BEPb/image_to_ascii
   $ cd image_to_ascii
   ```

### Aplicando o repositório
* Instale as dependências de um arquivo, para isto, insira o seguinte código na linha de comando:

```shell
$ pip3 install -r requirements.txt
````

* Meio geral de inicializar o programa

```shell
$ python3 img_to_txt_rus.py [file/url] [size]
```

* Argumentos:

```shell
[file/url]: Arquivo local ou uma URL de imagem online.
[size]: A largura do texto de saída em caracteres - um número inteiro, Quanto maior o tamanho, mais clara a imagem.
```

### Exemplo
```shell
$ python3 img_to_txt.py https://i.postimg.cc/t4Cmn7wC/py.png
```

Ao executar este comando, você receberá um arquivo na atual pasta 'texts' chamado `out.txt` e você verá a saída no console:


<img src="./pictures/py.png" alt="Bot logo" width="300" height="356.5">

<img src="./pictures/png.png" alt="Bot logo" width="600" height="600">


## Conversor de vído para texto
O princípio é similar, exceto que o arquivo de texto resultante não existe. 

```commandline
cd C:\Users\root\PycharmProjects\image_to_ascii 
python video_to_txt.py animations\filin.gif 150
```

<img src="./animations/filin.gif" alt="Bot logo" width="800" height="600">

<img src="./animations/gif.gif" alt="Bot logo" width="800" height="600">



### Licença
[Licença MIT](LICENSE)

================================================
FILE: README.ru.md
================================================
<p>
  <img  src="https://img.shields.io/github/stars/BEPb/image_to_ascii" />
  <img src="https://img.shields.io/github/contributors/BEPb/image_to_ascii" />
  <img src="https://img.shields.io/github/last-commit/BEPb/image_to_ascii" />
  <img src="https://visitor-badge.laobi.icu/badge?page_id=BEPb.image_to_ascii" />
  <img src="https://img.shields.io/github/languages/count/BEPb/image_to_ascii" />
  <img src="https://img.shields.io/github/languages/top/BEPb/image_to_ascii" />

  <img src="https://img.shields.io/badge/license-MIT-blue.svg?color=f64152" />
  <img  src="https://img.shields.io/github/issues/BEPb/image_to_ascii" />
  <img  src="https://img.shields.io/github/issues-pr/BEPb/image_to_ascii" />
</p>


# Преобразования изображения в txt-файл
Читать на других языках: [English](README.md), [हिन्दी](README.hindi.md), [中國人](README.chinese.md), [Português](README.portuguese.md)


## Как это работает?

Все очень просто: вы либо скачиваете файл-картинку или указываете ее ссылку при запуске скрипта на питоне, а на 
выходе получаете текстовый файл, а также сразу сможете просмотреть в командной строке как это будет выглядесть 
результат Вашего преобразования.

## Порядок подготовки и работы с ботом

* Клонировать репозиторий либо скачать архив из github или при помощи следующих команд в командной строке
   ```commandline
   $ cmd
   $ git clone https://github.com/BEPb/image_to_ascii
   $ cd image_to_ascii
   ```


### Применение репозитория
* Устанавливаем зависимости из файла, для этого в командной строке введите следующий код:

```shell
$ pip3 install -r requirements.txt
````

* общая форма запуска программы:

```shell
$ python3 img_to_txt_rus.py [file/url] [size]
```

* аргументы:

```shell
[file/url]: Путь к локальному файлу или URL-адрес онлайн-изображения.
[size]: Ширина вывода txt изображения в символах - целое число, Чем больше размер, тем четче картинка .
```

### Пример
```shell
$ python3 img_to_txt_rus.py https://i.postimg.cc/t4Cmn7wC/py.png
```
Выполнив эту команду, вы получите файл в текущей папке 'texts' с именем `out.txt`, и вы увидите вывод строки в консоли:

<img src="./pictures/py.png" alt="Bot logo" width="300" height="356.5">

<img src="./pictures/png.png" alt="Bot logo" width="600" height="600">


## Программа преобразования видео в текст
Принцип аналагичный, за исключением того, что итогового текстового файла не существует

```commandline
cd C:\Users\root\PycharmProjects\image_to_ascii  # переходим в дирректорию со скриптом
python video_to_txt_rus.py animations\filin.gif 150  # запускаем скрипт
```

<img src="./animations/filin.gif" alt="Bot logo" width="800" height="600">

<img src="./animations/gif.gif" alt="Bot logo" width="800" height="600">



### Лицензия
[MIT licence](LICENSE)


================================================
FILE: img_to_txt.py
================================================
"""
Python 3.10 image to text conversion program
The image can be downloaded both from a file and from the Internet.
File name img_to_txt_rus.py

Version: 0.1
Author: Andrej Marinchenko
Date: 2023-02-11
"""

from PIL import Image
import numpy as np
import requests
import sys

txt_file = f'texts/out.txt'
# img_file = ['-', f'pictures/superman.jpg', 90]
img_file = ['-', f'pictures/py.jpg', 80]

abc = '##@@MMBB88NNHHOOGGPPEEXXFFVVYY22ZZCC77LLjjll11rrii;;;:::....  '
l = 256 / len(abc)


def remove_transparency(im, bg_colour=(255, 255, 255)):
    if im.mode in ('RGBA', 'LA') or (im.mode == 'P' and 'transparency' in im.info):
        alpha = im.convert('RGBA').split()[-1]
        bg = Image.new("RGBA", im.size, bg_colour + (255,))
        bg.paste(im, mask=alpha)
        return bg
    else:
        return im

def pixel_to_black(fp, weight):
    try:
        img = Image.open(fp)
    except:
        print('Please enter the correct path or image URL.')
        return
    img = remove_transparency(img)
    img = img.convert("L")
    im_w, im_h = img.size
    img = np.array(img)
    h, w = img.shape
    weight_w = weight if w >= weight else w
    weight_h = weight if h >= weight else h
    weight = weight_w if weight_w < weight_h else weight_h
    t_w = weight
    t_h = weight / (im_w / im_h) / 2
    width_times = int(w / t_w) if int(w / t_w) != 0 else 1
    high_times = int(h / t_h) if int(h / t_h) != 0 else 1
    tmp_high = []
    for high_index in range(int(h / high_times)):
        tmp_width = []
        for width_index in range(int(w / width_times)):
            tmp_block = []
            for y in range((high_index * high_times), ((high_index + 1) * high_times)):
                for x in range(width_index * width_times, (width_index + 1) * width_times):
                    tmp_block.append(img[y, x])
            avg_tmp_block = sum(tmp_block) / len(tmp_block)
            tmp_width.append(avg_tmp_block)
        tmp_high.append(tmp_width)
    return tmp_high

def black_to_alphabet(rgb_list):
    tmp_high = ''
    for i in rgb_list:
        tmp_width = ''
        for ii in i:
            a = abc[int(ii / l)]
            tmp_width += a
        tmp_width += '\n'
        tmp_high += tmp_width
    return tmp_high

def paint(uri, weight):
    if uri.startswith('http'):
        img = get_img(uri)
    else:
        img = uri
    rgb_list = pixel_to_black(img, weight)
    if not rgb_list:
        return
    s = black_to_alphabet(rgb_list)
    with open(txt_file, 'w', encoding='utf-8') as f:
        f.write(s)
    return s

def get_img(url):
    response = requests.get(url)
    if response.status_code == 200:
        with open(f'pictures/temp.png', 'wb') as f:
            for chunk in response.iter_content(1024):
                f.write(chunk)
            return f'pictures/temp.png'

def main(args):
    try:
        uri = args[1]
        assert type(uri) == str
    except:
        uri = 'https://i.postimg.cc/t4Cmn7wC/py.png'
    try:
        weight = int(args[2])
        assert type(weight) == int
    except:
        weight = 80
    s = paint(uri, weight=weight)
    if not s:
        return
    print(s)

if __name__ == '__main__':
    main(sys.argv)
    # main(img_file)

================================================
FILE: img_to_txt_rus.py
================================================
"""
Python 3.10 программа преобразования картинки в текст
Картинку можно загрузить как из файла так и из интернета
Название файла img_to_txt_rus.py

Version: 0.1
Author: Andrej Marinchenko
Date: 2023-02-11
"""

from PIL import Image
import numpy as np
import requests
import sys

txt_file = f'texts/out.txt'
# img_file = ['-', f'pictures/superman.jpg', 90]  # указываем адрес файла изображения для обработки и его конечный размер
img_file = ['-', f'pictures/py.jpg', 80]  # указываем адрес файла изображения для обработки и его конечный размер

abc = '##@@MMBB88NNHHOOGGPPEEXXFFVVYY22ZZCC77LLjjll11rrii;;;:::....  '
l = 256 / len(abc)

# функция определяет тип изображения
def remove_transparency(im, bg_colour=(255, 255, 255)):
    # Обрабатывать только в том случае, если изображение имеет прозрачность
    if im.mode in ('RGBA', 'LA') or (im.mode == 'P' and 'transparency' in im.info):

        # Необходимо преобразовать в RGBA, если формат LA из-за ошибки в PIL
        alpha = im.convert('RGBA').split()[-1]

        # Создайте новое фоновое изображение нашего матового цвета.
        # Должен быть RGBA, потому что вставка требует, чтобы оба изображения имели одинаковый формат
        bg = Image.new("RGBA", im.size, bg_colour + (255,))
        bg.paste(im, mask=alpha)
        return bg
    else:
        return im

# преобразование картинки
def pixel_to_black(fp, weight):
    try:
        img = Image.open(fp)
    except:
        print('Введите правильный путь или URL изображения, пожалуйста.')
        return
    img = remove_transparency(img)
    img = img.convert("L")
    im_w, im_h = img.size
    img = np.array(img)
    h, w = img.shape
    # ширина
    weight_w = weight if w >= weight else w
    weight_h = weight if h >= weight else h
    weight = weight_w if weight_w < weight_h else weight_h
    # Максимальная ширина символа
    t_w = weight
    # Максимальная высота символов
    t_h = weight / (im_w / im_h) / 2
    width_times = int(w / t_w) if int(w / t_w) != 0 else 1
    high_times = int(h / t_h) if int(h / t_h) != 0 else 1

    tmp_high = []
    for high_index in range(int(h / high_times)):
        tmp_width = []
        for width_index in range(int(w / width_times)):
            tmp_block = []
            for y in range((high_index * high_times), ((high_index + 1) * high_times)):
                for x in range(width_index * width_times, (width_index + 1) * width_times):
                    tmp_block.append(img[y, x])
            avg_tmp_block = sum(tmp_block) / len(tmp_block)
            tmp_width.append(avg_tmp_block)
        tmp_high.append(tmp_width)
    return tmp_high


def black_to_alphabet(rgb_list):
    tmp_high = ''
    for i in rgb_list:
        tmp_width = ''
        for ii in i:
            a = abc[int(ii / l)]
            tmp_width += a
        tmp_width += '\n'
        tmp_high += tmp_width
    return tmp_high

# функция преобразования изображения в текст
def paint(uri, weight):
    if uri.startswith('http'):  # если указана ссылка в интернете, то скачиваем изображение
        print('Распознана ссылка')
        img = get_img(uri)
    else:  # иначе указана ссылка на локальное изображение (файл)
        print('Распознан файл')
        img = uri
    rgb_list = pixel_to_black(img, weight)
    if not rgb_list:
        return
    s = black_to_alphabet(rgb_list)
    with open(txt_file, 'w', encoding='utf-8') as f:
        f.write(s)
    return s

# функция взятия изображения
def get_img(url):
    print('Загрузка изображения из Интернета, пожалуйста, подождите.')
    response = requests.get(url)
    if response.status_code == 200:
        with open(f'pictures/temp.png', 'wb') as f:
            for chunk in response.iter_content(1024):
                f.write(chunk)
            return f'pictures/temp.png'

'''Главная функция'''
def main(args):  # функция принимает аргументы
    try:
        print('Ваша ссылка принята')
        uri = args[1]
        assert type(uri) == str
    except:
        # изображение по умолчанию, в случае если не задано иное
        print('Вы не указали ссылку на скачивание, по этой причине будет загружено изображение по умолчанию...')
        uri = 'https://i.postimg.cc/t4Cmn7wC/py.png'
    try:
        weight = int(args[2])  # второй аргумент, это ширина изображения текста в символах
        assert type(weight) == int  # проверяем что заданное число - целое
    except:
        weight = 80  # если ширина не задана, то по умолчанию 80 символов
    s = paint(uri, weight=weight)
    if not s:
        return
    print(s)  # печать в командной строке преобразованного изображения в текст

# проверка на главную программу и запуск главной функции
if __name__ == '__main__':
    main(sys.argv)  # запускаем главную функцию с аргументами при запуске программы
    # main(img_file)  # запускаем главную функцию с картинкой из папки


================================================
FILE: texts/out.txt
================================================
                                                                                   
                                                                                   
                                                                                   
                                                                                   
                                                                                   
                                                                                   
                                                                                   
                                                                                   
                                                                                   
                                  .iljjjjjjjjjlr:                                  
                                rYXXXXXXXXXXXXXXXVj.                               
                               ZX7:.;YXXXXXXXXXXXXXY.                              
                              1XXr   ZXXXXXXXXXXXXXXC                              
                              LXXXY2FXXXXXXXXXXXXXXXY                              
                              r7777777777YXXXXXXXXXXY                              
                      ijC2222222222222222VXXXXXXXXXXY :::::..                      
                    lFXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXY ;iiiiii;.                    
                   7XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXC iiiiiiiii;                   
                  :XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXY.:iiiiiiiiii.                  
                  ;XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXYl.:iiiiiiiiiii:                  
                  ;XXXXXXXXXXXXXXX27jlllllllll1i:.:iiiiiiiiiiiii:                  
                  ;XXXXXXXXXXXXYr.::;;;;;;;;;;;iiiiiiiiiiiiiiiii:                  
                  ;XXXXXXXXXXXl.;iiiiiiiiiiiiiiiiiiiiiiiiiiiiiii:                  
                  .VXXXXXXXXXL ;iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii.                  
                   :YXXXXXXXX::iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii:                   
                     rZFXXXXX.:iiiiiiiiiiiiiiiiiiiiiiiiiiiiii:.                    
                        .:;;; :iiiiiiiiii;..................                       
                              :iiiiiiiiiiiiiiiiiiiii;                              
                              :iiiiiiiiiiiiiii:..;ii;                              
                              .iiiiiiiiiiiiii;    ii:                              
                               .iiiiiiiiiiiiii;::;i:                               
                                 .;iiiiiiiiiiiii;:.                                
                                     .........                                     
                                                                                   
                                                                                   
                                                                                   
                                                                                   
                                                                                   
                                                                                   
                                                                                   
                                                                                   


================================================
FILE: video_to_txt.py
================================================
"""
Python 3.10 программа преобразования видео в текст
видео можно загрузить как из файла так и из интернета
Название файла video_to_txt.py

Version: 0.1
Author: Andrej Marinchenko
Date: 2023-02-11
"""
import cv2
from PIL import Image
import numpy as np
import time
import sys

abc = '@MWNHB8$06XFVYZ27>1jli!;:,. '
l = 256 / len(abc)

def remove_transparency(im, bg_colour=(255, 255, 255)):
    if im.mode in ('RGBA', 'LA') or (im.mode == 'P' and 'transparency' in im.info):
        alpha = im.convert('RGBA').split()[-1]
        bg = Image.new("RGBA", im.size, bg_colour + (255,))
        bg.paste(im, mask=alpha)
        return bg

    else:
        return im

def img2pixel(img, charwidth=100):
    img = img.convert("L")
    w, h = img.size
    img = img.resize((charwidth, int(charwidth * (h / w) / 2.4)))
    data = np.array(img)
    return data


def pixel2char(data):
    chars = '\n\n'
    for row in data:
        for pixel in row:
            a = abc[int(pixel / l)]
            chars += a
        chars += '\n'
    return chars + '\n'


def main(args):
    start = time.time()
    if len(args) != 3:
        return
    vcap = cv2.VideoCapture(args[1])
    width = vcap.get(cv2.CAP_PROP_FRAME_WIDTH)  # вещественное число
    height = vcap.get(cv2.CAP_PROP_FRAME_HEIGHT)  # вещественное число
    fps = vcap.get(cv2.CAP_PROP_FPS)
    print(width, height, fps)

    currentframe = 0
    while (True):
        t1 = time.time()
        ret, frame = vcap.read()
        if ret:
            pilimg = Image.fromarray(frame)
            data = img2pixel(pilimg, charwidth=int(args[2]))
            s = pixel2char(data=data)
            print(s)
            currentframe += 1
        else:
            break

        time2sleep = (1 / fps) - (time.time() - t1)
        if time2sleep > 0: time.sleep(time2sleep)

    # Освободите пространство и окна
    vcap.release()
    cv2.destroyAllWindows()

if __name__ == '__main__':
    main(sys.argv)


================================================
FILE: video_to_txt_rus.py
================================================
"""
Python 3.10 программа преобразования видео в текст
видео можно загрузить как из файла так и из интернета
Название файла video_to_txt_rus.py

Version: 0.1
Author: Andrej Marinchenko
Date: 2023-02-11
"""
import cv2
from PIL import Image
import numpy as np
import time
import sys

abc = '@MWNHB8$06XFVYZ27>1jli!;:,. '
l = 256 / len(abc)


def remove_transparency(im, bg_colour=(255, 255, 255)):
    if im.mode in ('RGBA', 'LA') or (im.mode == 'P' and 'transparency' in im.info):
        alpha = im.convert('RGBA').split()[-1]
        bg = Image.new("RGBA", im.size, bg_colour + (255,))
        bg.paste(im, mask=alpha)
        return bg

    else:
        return im


def img2pixel(img, charwidth=100):
    img = img.convert("L")
    w, h = img.size
    img = img.resize((charwidth, int(charwidth * (h / w) / 2.4)))
    data = np.array(img)
    return data


def pixel2char(data):
    chars = '\n\n'
    for row in data:
        for pixel in row:
            a = abc[int(pixel / l)]
            chars += a
        chars += '\n'
    return chars + '\n'


def main(args):
    start = time.time()
    if len(args) != 3:
        print("Использование: video_to_txt ширина символа видеопути")
        return

    # Получите информацию о ширине, высоте и частоте кадров видео
    vcap = cv2.VideoCapture(args[1])
    width = vcap.get(cv2.CAP_PROP_FRAME_WIDTH)  # вещественное число
    height = vcap.get(cv2.CAP_PROP_FRAME_HEIGHT)  # вещественное число
    fps = vcap.get(cv2.CAP_PROP_FPS)
    print(width, height, fps)

    # начать цикл по кадрам
    currentframe = 0
    while (True):
        t1 = time.time()
        ret, frame = vcap.read()
        if ret:
            pilimg = Image.fromarray(frame)
            data = img2pixel(pilimg, charwidth=int(args[2]))
            s = pixel2char(data=data)
            print(s)
            currentframe += 1
        else:
            break

        # Время сна составляет одну долю секунды от кадров в секунду минус время, в течение которого этот кадр уже использовался.
        time2sleep = (1 / fps) - (time.time() - t1)
        if time2sleep > 0: time.sleep(time2sleep)

    # Освободите пространство и окна
    vcap.release()
    cv2.destroyAllWindows()
    print("Прошедшее время:", time.time() - start)


if __name__ == '__main__':
    main(sys.argv)
Download .txt
gitextract_25iimfmq/

├── LICENSE
├── README.chinese.md
├── README.hindi.md
├── README.md
├── README.portuguese.md
├── README.ru.md
├── img_to_txt.py
├── img_to_txt_rus.py
├── requirements.txt
├── texts/
│   └── out.txt
├── video_to_txt.py
└── video_to_txt_rus.py
Download .txt
SYMBOL INDEX (20 symbols across 4 files)

FILE: img_to_txt.py
  function remove_transparency (line 24) | def remove_transparency(im, bg_colour=(255, 255, 255)):
  function pixel_to_black (line 33) | def pixel_to_black(fp, weight):
  function black_to_alphabet (line 64) | def black_to_alphabet(rgb_list):
  function paint (line 75) | def paint(uri, weight):
  function get_img (line 88) | def get_img(url):
  function main (line 96) | def main(args):

FILE: img_to_txt_rus.py
  function remove_transparency (line 24) | def remove_transparency(im, bg_colour=(255, 255, 255)):
  function pixel_to_black (line 40) | def pixel_to_black(fp, weight):
  function black_to_alphabet (line 76) | def black_to_alphabet(rgb_list):
  function paint (line 88) | def paint(uri, weight):
  function get_img (line 104) | def get_img(url):
  function main (line 114) | def main(args):  # функция принимает аргументы

FILE: video_to_txt.py
  function remove_transparency (line 19) | def remove_transparency(im, bg_colour=(255, 255, 255)):
  function img2pixel (line 29) | def img2pixel(img, charwidth=100):
  function pixel2char (line 37) | def pixel2char(data):
  function main (line 47) | def main(args):

FILE: video_to_txt_rus.py
  function remove_transparency (line 20) | def remove_transparency(im, bg_colour=(255, 255, 255)):
  function img2pixel (line 31) | def img2pixel(img, charwidth=100):
  function pixel2char (line 39) | def pixel2char(data):
  function main (line 49) | def main(args):
Condensed preview — 12 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (36K chars).
[
  {
    "path": "LICENSE",
    "chars": 1075,
    "preview": "MIT License\n\nCopyright (c) 2023 Andrej Marinchenko\n\nPermission is hereby granted, free of charge, to any person obtainin"
  },
  {
    "path": "README.chinese.md",
    "chars": 1990,
    "preview": "<p>\n  <img  src=\"https://img.shields.io/github/stars/BEPb/image_to_ascii\" />\n  <img src=\"https://img.shields.io/github/c"
  },
  {
    "path": "README.hindi.md",
    "chars": 2639,
    "preview": "<p>\n  <img  src=\"https://img.shields.io/github/stars/BEPb/image_to_ascii\" />\n  <img src=\"https://img.shields.io/github/c"
  },
  {
    "path": "README.md",
    "chars": 2680,
    "preview": "<p>\n  <img  src=\"https://img.shields.io/github/stars/BEPb/image_to_ascii\" />\n  <img src=\"https://img.shields.io/github/c"
  },
  {
    "path": "README.portuguese.md",
    "chars": 2664,
    "preview": "<p>\n  <img  src=\"https://img.shields.io/github/stars/BEPb/image_to_ascii\" />\n  <img src=\"https://img.shields.io/github/c"
  },
  {
    "path": "README.ru.md",
    "chars": 2749,
    "preview": "<p>\n  <img  src=\"https://img.shields.io/github/stars/BEPb/image_to_ascii\" />\n  <img src=\"https://img.shields.io/github/c"
  },
  {
    "path": "img_to_txt.py",
    "chars": 3210,
    "preview": "\"\"\"\nPython 3.10 image to text conversion program\nThe image can be downloaded both from a file and from the Internet.\nFil"
  },
  {
    "path": "img_to_txt_rus.py",
    "chars": 4834,
    "preview": "\"\"\"\nPython 3.10 программа преобразования картинки в текст\nКартинку можно загрузить как из файла так и из интернета\nНазва"
  },
  {
    "path": "texts/out.txt",
    "chars": 3444,
    "preview": "                                                                                   \n                                    "
  },
  {
    "path": "video_to_txt.py",
    "chars": 1946,
    "preview": "\"\"\"\nPython 3.10 программа преобразования видео в текст\nвидео можно загрузить как из файла так и из интернета\nНазвание фа"
  },
  {
    "path": "video_to_txt_rus.py",
    "chars": 2299,
    "preview": "\"\"\"\nPython 3.10 программа преобразования видео в текст\nвидео можно загрузить как из файла так и из интернета\nНазвание фа"
  }
]

// ... and 1 more files (download for full content)

About this extraction

This page contains the full source code of the BEPb/image_to_ascii GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 12 files (28.8 KB), approximately 8.0k tokens, and a symbol index with 20 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!