Opencv学习笔记(五):cv2.putText()和cv2.rectangle()详细理解

一:cv2.putText()

函数介绍:cv2.putText(img, str(i), (123,456), font, 2, (0,255,0), 3)
参数意思:图片,添加的文字,左上角坐标,字体,字体大小(数值越大,字体越大,可以为小数),颜色,字体粗细(越大越粗)
字体选择:FONT_HERSHEY_SIMPLEX、normal size sans-serif font、small size sans-serif font、FONT_HERSHEY_COMPLEX

二:cv2.rectangle()

函数介绍:cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
参数意思:图片,左上点坐标,右下点坐标,rgb颜色,线的宽度

三:实战例子

import cv2
import math
class ssdface():
    def __init__(self, framework='caffe', threshold=0.7):
        if framework == 'caffe':
            self.net = cv2.dnn.readNetFromCaffe('D:\pycharm\compare_three_module\SSDV2_detect_face/deploy.prototxt', 'D:/pycharm\compare_three_module/SSDV2_detect_face/res10_300x300_ssd_iter_140000_fp16.caffemodel')
        self.conf_threshold = threshold
        self.framework = framework
    def detect(self, frame):
        frameOpencvDnn = frame.copy()
        frameHeight = frameOpencvDnn.shape[0]
        frameWidth = frameOpencvDnn.shape[1]
        if self.framework == 'caffe':
            blob = cv2.dnn.blobFromImage(frameOpencvDnn, 1.0, (300, 300), [104, 117, 123], False, False)
        else:
            blob = cv2.dnn.blobFromImage(frameOpencvDnn, 1.0, (300, 300), [104, 117, 123], True, False)
        self.net.setInput(blob)
        detections = self.net.forward()
        face_rois = []
        confidence1=[]
        for i in range(detections.shape[2]):
            confidence = detections[0, 0, i, 2]
            if confidence > self.conf_threshold:
                confidence1.append(confidence)
                x1 = int(detections[0, 0, i, 3] * frameWidth)
                y1 = int(detections[0, 0, i, 4] * frameHeight)
                print(x1,y1)
                # p1=(x1,y1)
                x2 = int(detections[0, 0, i, 5] * frameWidth)
                y2 = int(detections[0, 0, i, 6] * frameHeight)
                # p2=(x2,y2)
                # cv2.rectangle(frameOpencvDnn, (x1, y1), (x2, y2), (255, 0, 0), 2)
                title = math.floor(confidence * 10 ** 2) / (10 ** 2)
                print(title)
                cv2.rectangle(frameOpencvDnn,(x1, y1), (x2, y2), (0, 0, 255), thickness=2)
                # cv2.putText(frameOpencvDnn,title, (x1,y1), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 1)
                cv2.putText(frameOpencvDnn, 'acc:' + str(title), (x1+10, y1-10),cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0, 0, 255),1)
                face_rois.append(frame[y1:y2, x1:x2])
                # cv2.imshow('1',frame[y1:y2, x1:x2])
                # cv2.waitKey(0)
        return frameOpencvDnn, face_rois,confidence1
    def get_face(self, frame):
        frameOpencvDnn = frame.copy()
        frameHeight = frameOpencvDnn.shape[0]
        frameWidth = frameOpencvDnn.shape[1]
        if self.framework == 'caffe':
            blob = cv2.dnn.blobFromImage(frameOpencvDnn, 1.0, (300, 300), [104, 117, 123], False, False)
        else:
            blob = cv2.dnn.blobFromImage(frameOpencvDnn, 1.0, (300, 300), [104, 117, 123], True, False)
        self.net.setInput(blob)
        detections = self.net.forward()
        boxs, face_rois = [], []
        for i in range(detections.shape[2]):
            confidence = detections[0, 0, i, 2]
            if confidence > self.conf_threshold:
                x1 = int(detections[0, 0, i, 3] * frameWidth)
                y1 = int(detections[0, 0, i, 4] * frameHeight)
                x2 = int(detections[0, 0, i, 5] * frameWidth)
                y2 = int(detections[0, 0, i, 6] * frameHeight)
                boxs.append((x1, y1, x2, y2))
                face_rois.append(frame[y1:y2, x1:x2])
        return boxs, face_rois

if __name__ == "__main__" :
    import time
    ssdface_detect = ssdface(framework='caffe')
    imgpath = 's_l.jpg'
    save_path='D:/pycharm/compare_three_module/result/'
    srcimg = cv2.imread(imgpath)
    a = time.time()
    drawimg, face_rois,confidence = ssdface_detect.detect(srcimg)
    b = time.time()
    time = round(b - a, 3)  # 保留一位小数 2为两位
    cv2.putText(drawimg, 'time:' + str(time), (20, 40), cv2.FONT_HERSHEY_SIMPLEX, 1,(0, 0, 255))
    cv2.namedWindow('SSDV2detect', cv2.WINDOW_NORMAL)
    cv2.imshow('SSDV2detect', drawimg)
    cv2.imwrite(save_path + 'SSDV2.jpg', drawimg)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

运行结果
在这里插入图片描述

### 解决 Python OpenCV `cv2.putText` 函数显示中文乱码的方法 当使用 OpenCV 的 `cv2.putText()` 方法尝试绘制中文字符时,可能会遇到乱码问题。这是因为默认情况下,OpenCV 并不支持 UTF-8 编码的字符串以及复杂的字体渲染。 一种有效的解决方案是利用 Pillow 库来处理文字绘制部分,再将其转换回 OpenCV 图像格式。具体实现如下: #### 使用 Pillow NumPy 处理中文文本 通过引入 Pillow 来创建带有指定中文字体的文字图片,并最终转成适合 OpenCV 显示的形式[^1]。 ```python from PIL import Image, ImageDraw, ImageFont import numpy as np import cv2 def put_chinese_text(image_path, text, position=(50, 50)): # 加载原始图像并准备画布 img_bgr = cv2.imread(image_path) # 将 BGR 色彩模式转化为 RGB 方便后续操作 img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB) # 构建PIL.Image对象用于绘图 pil_image = Image.fromarray(img_rgb) draw = ImageDraw.Draw(pil_image) # 设置字体样式与大小 font_style = ImageFont.truetype("simhei.ttf", 40, encoding="utf-8") # 在图像上写入汉字 draw.text(position, text, fill=(255, 0, 0), font=font_style) # 把修改过的图像重新转化回numpy数组形式供opencv读取 final_img_np_array = np.array(pil_image) # 返回至BGR色彩空间以便于保存或展示 result_img = cv2.cvtColor(final_img_np_array, cv2.COLOR_RGB2BGR) return result_img if __name__ == "__main__": output = put_chinese_text('example.jpg', '你好世界') cv2.imshow('Result with Chinese Text', output) cv2.waitKey(0) ``` 此方法绕过了 OpenCV 对复杂字体的支持不足的问题,借助第三方库实现了高质量的中文文本渲染效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZZY_dl

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值