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

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

相关推荐
不是万能的豆学长3 小时前
filetidy 文件整理助手:一键归类 + 规范重命名(Python 零依赖单文件工具)
大数据·开发语言·python·技术美术
gCode Teacher 格码致知4 小时前
Pandas教学-18:number与numeric的区别
python·pandas
梦想不只是梦与想7 小时前
Python 中subprocess 模块:执行外部命令
python·subprocess·调用外部命令
懂点Tech7 小时前
ctfshow MISC入门图片篇(信息附加):misc41解题思路
开发语言·python
catchadmin8 小时前
PHP 8.7 协程新提案 让跨协程代码共享请求身份
开发语言·php
念何架构之路9 小时前
go-grpc设计思想
开发语言·后端·golang
酷炫码神9 小时前
Day 10|Pinia 状态管理:把散落在各组件的数据,收进一个全局仓库
android·开发语言·javascript
Elastic 中国社区官方博客10 小时前
我们如何通过 70 多个拉取请求,将 OpenTelemetry Java agent 迁移到 invokedynamic
java·大数据·开发语言·elasticsearch·搜索引擎·全文检索·es
tyn18810 小时前
记录本地安装nacos服务的方法及异常
java·开发语言
步行cgn11 小时前
Spring MVC 视图机制的核心接口与类
java·开发语言·后端·spring·mvc