Convierte tus imágenes en forma con ASCII para personalizar tus Script Python

avatar
(Edited)


En la publicación anterior, hablé sobre la biblioteca Art de Python, la cual convierte palabras u oraciones a ASCII. Hoy quiero compartir dos bibliotecas, con las cuales podemos crear formas con ASCII a partir de imágenes. Estas bibliotecas son PIL o PILLOW y NumPy. PILLOW , es creada para abrir, manipular y guardar archivos en formato de imagen, es de gratuita y de código abierto. NumPy, es una biblioteca poderosa para crear matrices multidimensionales y operaciones matemáticas, también es de código abierto y cuenta con una gran cantidad de colaboradores alrededor del mundo.

El flujo del script es el siguiente:

  • Se carga la imagen con la biblioteca Pillow y se redimensiona el tamaño.

  • Se transforma la imagen en un arreglo NumPy tomando cada pixel.

  • Luego los se genera la imagen ASCII a partir del arreglo NumPy anterior.

  • Se abre el ascii_logo.txt y se guarda la imagen ASCII para después abrirlo e imprimirlo en la terminal.


Fuente de la imagen

Código fuente:


from PIL import Image
import numpy as np

# Cargar imagen y convertir a escala de grises

imagen = Image.open('logo-hive.png').convert('L')
nuevo_ancho = 80  # El nuevo ancho deseado para la imagen
nuevo_alto = 35
imagen = imagen.resize((nuevo_ancho, nuevo_alto))  # Redimensionar la imagen


# Convertir imagen en arreglo numpy y normalizar valores
pixels = np.array(imagen.getdata())
pixels = (pixels - np.min(pixels)) / (np.max(pixels) - np.min(pixels))

# Generar imagen ASCII art
caracteres = np.asarray(list(' .,:;irsXA253hMHGS#9B&@'))
imagen_ascii = caracteres[(pixels * (len(caracteres) - 1)).astype(int)]
imagen_ascii = imagen_ascii.reshape(imagen.size[::-1])

# Guardar imagen ASCII art como archivo de texto
with open('ascii_logo.txt', 'w') as archivo:
archivo.write('\n'.join([''.join(fila) for fila in imagen_ascii]))


with open('ascii_logo.txt', 'r') as f:
ascii_logo = f.read()
print(ascii_logo)


Salida de ejemplo:


Estructura del proyecto

Para instalar las librerías use los siguientes comando:


Como pueden ver es muy sencillo en el script y se puede integrar a cualquier proyecto Python para ejecutar en la terminal, especialmente para aplicaciones CLI. También existe otra biblioteca que puede sustituir a Pillow, esta es Imageio. Los invito a probar ambas bibliotecas y compartir aquí sus imágenes ASCII.


Las imágenes son mías o capturas de pantalla tomadas por mí, a menos que se indiquen fuentes externas.


Discord: alberto0607#6813
Twitter: alberto_0607



0
0
0.000
5 comments
avatar

Hey @alberto0607!
Actifit (@actifit) is Hive's flagship Move2Earn Project. We've been building on hive for almost 5 years now and have an active community of 7,000+ subscribers & 600+ active users.
We provide many services on top of hive, supportive to both hive and actifit vision. We've also partnered with many great projects and communities on hive.
We're looking for your vote to support actifit's growth and services on hive blockchain.
Click one of below links to view/vote on the proposal:

  • peakd
  • ecency
  • hivesigner
  • 0
    0
    0.000
    avatar

    Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

    Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

    You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support. 
     

    0
    0
    0.000
    avatar
    Tu post ha sido votado por @celf.magazine, proyecto curatorial y revista digital sobre arte y cultura en Hive. Únete a nuestra comunidad y comparte tu talento con nosotros.
    Your post has been voted by @celf.magazine, curatorial project and digital magazine about art and culture in Hive. Join our community and share your talent with us.



    0
    0
    0.000