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

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

相关推荐
2501_930707785 分钟前
使用C#从 PowerPoint 演示文稿中提取图片
开发语言·c#·powerpoint
zhanghaha131427 分钟前
C# 系列教程_15 类 Class 保姆级系统教程(面向新手,大量示例 + 底层机理)
java·开发语言·c#
羲云网络10 小时前
GPT Image 2.6 海报改横竖版:文字安全区、排版分离与交付验收
图像处理·人工智能·python·aigc
曲径海盗11 小时前
【Python 学习第 65 天】字典基础
python·学习笔记·编程入门
Wellijohn11 小时前
Docker 瘦身、手写 MCP、异步并发:被问得最多的 12 个问题,一次答完
python·docker·mcp
VW_40414 小时前
csdn-2026-11-23-第一站踩坑
爬虫·python
yiangL_15 小时前
课后作业4:基于 Python 的古诗词词云可视化(P205)
开发语言·python
Dmz丶15 小时前
前端转 AI 100 天 Day 52:RAG 项目实战(一)——从零搭建企业知识库
python
geovindu16 小时前
rust: Functional Options Pattern
开发语言·后端·设计模式·rust·函数式选项模式·惯用法型模式
skywalk816317 小时前
把「假成功」赶出工具层:lightharness 两天升级复盘(4×5 模式矩阵 + 工具层 5 个缺陷)
开发语言·前端·人工智能·lightharness