Python相片图片编辑工具-翻转旋转亮度磨皮裁剪添加文字

简介: 这篇博客针对<<Python相片图片编辑工具-翻转旋转亮度磨皮裁剪添加文字>>编写代码,代码整洁,规则,易读。 学习与应用推荐首选。

程序示例精选

Python相片图片编辑工具-翻转旋转亮度磨皮裁剪添加文字

如需安装运行环境或远程调试,可点击右边主头像昵称进入个人主页查看博主联系方式,由专业技术人员远程协助!


前言

这篇博客针对<<Python相片图片编辑工具-翻转旋转亮度磨皮裁剪添加文字>>编写代码,代码整洁,规则,易读。 学习与应用推荐首选。


文章目录

一、所需工具软件

二、使用步骤

1. 引入库

2. 识别图像

3. 运行结果

三、在线协助

一、所需工具软件

1. Pycharm, Python

2. Qt, OpenCV

二、使用步骤

1.引入库

代码如下(示例):

from PyQt5 import QtWidgets
from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import QApplication, QWidget

image.gif

image.gif编辑

2.识别图像特征

代码如下(示例):

defdetect(save_img=False):
    source, weights, view_img, save_txt, imgsz = opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size
    webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(
        ('rtsp://', 'rtmp://', 'http://'))
    # Directories
    save_dir = Path(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok))  # increment run
    (save_dir / 'labels'if save_txt else save_dir).mkdir(parents=True, exist_ok=True)  # make dir# Initialize
    set_logging()
    device = select_device(opt.device)
    half = device.type != 'cpu'# half precision only supported on CUDA# Load model
    model = attempt_load(weights, map_location=device)  # load FP32 model
    stride = int(model.stride.max())  # model stride
    imgsz = check_img_size(imgsz, s=stride)  # check img_sizeif half:
        model.half()  # to FP16# Second-stage classifier
    classify = Falseif classify:
        modelc = load_classifier(name='resnet101', n=2)  # initialize
        modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']).to(device).eval()
    # Set Dataloader
    vid_path, vid_writer = None, Noneif webcam:
        view_img = check_imshow()
        cudnn.benchmark = True# set True to speed up constant image size inference
        dataset = LoadStreams(source, img_size=imgsz, stride=stride)
    else:
        save_img = True
        dataset = LoadImages(source, img_size=imgsz, stride=stride)
    # Get names and colors
    names = model.module.names ifhasattr(model, 'module') else model.names
    colors = [[random.randint(0, 255) for _ inrange(3)] for _ in names]
    # Run inferenceif device.type != 'cpu':
        model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters())))  # run once
    t0 = time.time()
    for path, img, im0s, vid_cap in dataset:
        img = torch.from_numpy(img).to(device)
        img = img.half() if half else img.float()  # uint8 to fp16/32
        img /= 255.0# 0 - 255 to 0.0 - 1.0if img.ndimension() == 3:
            img = img.unsqueeze(0)
        # Inference
        t1 = time_synchronized()
        pred = model(img, augment=opt.augment)[0]
        # Apply NMS
        pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=opt.classes, agnostic=opt.agnostic_nms)
        t2 = time_synchronized()
        # Apply Classifierif classify:
            pred = apply_classifier(pred, modelc, img, im0s)
        # Process detectionsfor i, det inenumerate(pred):  # detections per imageif webcam:  # batch_size >= 1
                p, s, im0, frame = path[i], '%g: ' % i, im0s[i].copy(), dataset.count
            else:
                p, s, im0, frame = path, '', im0s, getattr(dataset, 'frame', 0)
            p = Path(p)  # to Path
            save_path = str(save_dir / p.name)  # img.jpg
            txt_path = str(save_dir / 'labels' / p.stem) + (''if dataset.mode == 'image'elsef'_{frame}')  # img.txt
            s += '%gx%g ' % img.shape[2:]  # print string
            gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]  # normalization gain whwhiflen(det):
                # Rescale boxes from img_size to im0 size
                det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
                # Write resultsfor *xyxy, conf, cls inreversed(det):
                    if save_txt:  # Write to file
                        xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()  # normalized xywh
                        line = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh)  # label formatwithopen(txt_path + '.txt', 'a') as f:
                            f.write(('%g ' * len(line)).rstrip() % line + '\n')
                    if save_img or view_img:  # Add bbox to image
                        label = f'{names[int(cls)]}{conf:.2f}'
                        plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3)
            # Print time (inference + NMS)print(f'{s}Done. ({t2 - t1:.3f}s)')
            # Save results (image with detections)if save_img:
                if dataset.mode == 'image':
                    cv2.imwrite(save_path, im0)
                else:  # 'video'if vid_path != save_path:  # new video
                        vid_path = save_path
                        ifisinstance(vid_writer, cv2.VideoWriter):
                            vid_writer.release()  # release previous video writer
                        fourcc = 'mp4v'# output video codec
                        fps = vid_cap.get(cv2.CAP_PROP_FPS)
                        w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
                        h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
                        vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*fourcc), fps, (w, h))
                    vid_writer.write(im0)
    if save_txt or save_img:
        s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}"if save_txt else''print(f"Results saved to {save_dir}{s}")
    print(f'Done. ({time.time() - t0:.3f}s)')
    print(opt)
    check_requirements()
    with torch.no_grad():
        if opt.update:  # update all models (to fix SourceChangeWarning)for opt.weights in ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt']:
                detect()
                strip_optimizer(opt.weights)
        else:
            detect()

image.gif

image.gif编辑

3. 运行结果如下

image.gif编辑


三、在线协助:

如需安装运行环境或远程调试, 可点击右边 主头像 昵称 进入个人主页查看博主联系方式 ,由专业技术人员远程协助!
1)远程安装运行环境,代码调试
2)Qt, C++, Python入门指导
3)界面美化
4)软件制作


博主推荐文章:python人脸识别统计人数qt窗体-CSDN博客

博主推荐文章:Python Yolov5火焰烟雾识别源码分享-CSDN博客

                        Python OpenCV识别行人入口进出人数统计_python识别人数-CSDN博客

个人博客主页:alicema1111的博客_CSDN博客-Python,C++,网页领域博主

博主所有文章点这里:alicema1111的博客_CSDN博客-Python,C++,网页领域博主


相关文章
|
20天前
|
Python
26: 翻转数的和(python)
26: 翻转数的和(python)
|
1月前
|
程序员 数据安全/隐私保护 Python
Python:翻转字符串
Python:翻转字符串
|
1天前
|
数据可视化 数据挖掘 数据处理
statsmodels, Python 统计分析工具库!
statsmodels, Python 统计分析工具库!
7 1
|
1天前
|
开发者 Python
six,一个神奇的 Python 版本兼容工具库!
six,一个神奇的 Python 版本兼容工具库!
11 4
|
1天前
|
人工智能 Python
beets,一个有趣的 Python 音乐信息管理工具!
beets,一个有趣的 Python 音乐信息管理工具!
10 4
|
2天前
|
数据采集 数据可视化 数据挖掘
R语言与Python:比较两种数据分析工具
【4月更文挑战第25天】R语言和Python是目前最流行的两种数据分析工具。本文将对这两种工具进行比较,包括它们的历史、特点、应用场景、社区支持、学习资源、性能等方面,以帮助读者更好地了解和选择适合自己的数据分析工具。
|
4天前
|
Shell Python
python|闲谈2048小游戏和数组的旋转及翻转和转置
python|闲谈2048小游戏和数组的旋转及翻转和转置
21 1
|
8天前
|
机器学习/深度学习 数据挖掘 计算机视觉
python数据分析工具SciPy
【4月更文挑战第15天】SciPy是Python的开源库,用于数学、科学和工程计算,基于NumPy扩展了优化、线性代数、积分、插值、特殊函数、信号处理、图像处理和常微分方程求解等功能。它包含优化、线性代数、积分、信号和图像处理等多个模块。通过SciPy,可以方便地执行各种科学计算任务。例如,计算高斯分布的PDF,需要结合NumPy使用。要安装SciPy,可以使用`pip install scipy`命令。这个库极大地丰富了Python在科学计算领域的应用。
12 1
|
9天前
|
数据可视化 数据挖掘 Python
Python中数据分析工具Matplotlib
【4月更文挑战第14天】Matplotlib是Python的数据可视化库,能生成多种图表,如折线图、柱状图等。以下是一个绘制简单折线图的代码示例: ```python import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] plt.figure() plt.plot(x, y) plt.title(&#39;简单折线图&#39;) plt.xlabel(&#39;X轴&#39;) plt.ylabel(&#39;Y轴&#39;) plt.show() ```
13 1
|
9天前
|
数据采集 SQL 数据可视化
Python数据分析工具Pandas
【4月更文挑战第14天】Pandas是Python的数据分析库,提供Series和DataFrame数据结构,用于高效处理标记数据。它支持从多种数据源加载数据,包括CSV、Excel和SQL。功能包括数据清洗(处理缺失值、异常值)、数据操作(切片、过滤、分组)、时间序列分析及与Matplotlib等库集成进行数据可视化。其高性能底层基于NumPy,适合大型数据集处理。通过加载数据、清洗、分析和可视化,Pandas简化了数据分析流程。广泛的学习资源使其成为数据分析初学者的理想选择。
15 1