图像与文字的创意融合:使用Python进行视觉艺术创作

原图:

处理过的:

python 复制代码
import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont
import os

# 字体文件路径
vfont = './fonts/方正像素字体.ttf'

def text_paint(img_path, text, font_path, font_size):
    # 使用 OpenCV 加载图片
    img = cv2.imread(img_path)
    if img is None:
        raise Exception("无法加载图片,请检查图片路径是否正确")
    
    # 放大图片为原来的2倍
    img = cv2.resize(img, (img.shape[1]*2, img.shape[0]*2), interpolation=cv2.INTER_LINEAR)
    
    # 检查字体文件是否存在
    try:
        if os.path.exists(font_path):
            font = ImageFont.truetype(font_path, font_size)
        else:
            font = ImageFont.truetype(vfont, font_size)
    except Exception as e:
        print(f"加载字体失败: {e}")
        font = ImageFont.load_default()

    # 获取文字的实际大小
    test_text = text
    bbox = font.getbbox(test_text)
    char_width = bbox[2] - bbox[0]
    char_height = bbox[3] - bbox[1]

    # 创建一个新的白底图片(2倍大小)
    new_img = Image.new('RGB', (img.shape[1], img.shape[0]), 'white')
    draw = ImageDraw.Draw(new_img)
    
    # 遍历图片的每个字符位置,使用实际字符大小
    for y in range(0, img.shape[0], char_height):
        for x in range(0, img.shape[1], char_width):
            # 获取当前区域的平均颜色
            if y < img.shape[0] and x < img.shape[1]:
                # 计算区域范围
                y_end = min(y + char_height, img.shape[0])
                x_end = min(x + char_width, img.shape[1])
                # 获取区域的平均颜色
                region = img[y:y_end, x:x_end]
                avg_color = np.mean(region, axis=(0, 1))
                color = tuple(map(int, avg_color[::-1]))  # BGR转RGB并转为整数
                # 用平均颜色绘制文字
                draw.text((x, y), text, font=font, fill=color)
    
    # 保存和显示图片
    new_img.save('output.jpg')
    new_img.show()

# 使用示例
text_paint('./2.png', 'a', vfont, 8)

功能解析

  • 图片加载和放大:首先使用OpenCV加载图片,如果图片不存在则抛出异常。然后将图片放大到原来的两倍,以便在更大的画布上绘制。
  • 字体加载:检查指定的字体文件是否存在,如果不存在则使用备用字体。
  • 文字大小获取:获取指定文字的实际大小,以便确定在图片上绘制文字的间隔。
  • 新图片创建:创建一个新的白色背景图片,大小为原图片的两倍。
  • 颜色计算和文字绘制:遍历图片的每个区域,计算该区域的平均颜色,并用这种颜色在新图片上绘制文字。
  • 图片保存和显示:最后,将处理后的图片保存并显示。

这个函数可以用于各种创意项目,例如生成艺术效果的图片或者进行视觉设计实验。

相关推荐
mortimer1 小时前
安装NVIDIA Parakeet时,我遇到的两个Pip“小插曲”
python·github
@昵称不存在2 小时前
Flask input 和datalist结合
后端·python·flask
爱装代码的小瓶子2 小时前
数据结构之队列(C语言)
c语言·开发语言·数据结构
赵英英俊2 小时前
Python day25
python
东林牧之3 小时前
Django+celery异步:拿来即用,可移植性高
后端·python·django
何双新3 小时前
基于Tornado的WebSocket实时聊天系统:从零到一构建与解析
python·websocket·tornado
Maybe_ch3 小时前
.NET-键控服务依赖注入
开发语言·c#·.net
超浪的晨3 小时前
Java UDP 通信详解:从基础到实战,彻底掌握无连接网络编程
java·开发语言·后端·学习·个人开发
终焉暴龙王3 小时前
CTFHub web进阶 php Bypass disable_function通关攻略
开发语言·安全·web安全·php
AntBlack3 小时前
从小不学好 ,影刀 + ddddocr 实现图片验证码认证自动化
后端·python·计算机视觉