Opencv 基础用法
0.读取图片不同通道
#什么参数都不加默认都是3通道 A = cv2.imread("/tmp/p1/alpha/1000034000_3.png") A = A[:, :, 0] # 取单通道 alpha图 #如果为4通道带alpha通道 #加参数cv2.IMREAD_UNCHANGED fg_image_4 = cv2.imread(fg_path, cv2.IMREAD_UNCHANGED) alpha_ori = fg_image_4[:, :, 3] # 前景人像,alpha图 fg_image_ori = fg_image_4[:, :, :3] # 前景人像,三通道
1.读取一张图片 imread
import cv2 img = cv2.imread('/tmp/pix_000099738.jpg') font = cv2.FONT_HERSHEY_SIMPLEX print(img)
2.保存图片 imwrite
import cv2 img = cv2.imread('/tmp/pix_000099738.jpg') cv2.imwrite("/tmp/test1.jpg", img)
3.添加文字 putText
font = cv2.FONT_HERSHEY_SIMPLEX # 定义字体 imgzi = cv2.putText(img, '000', (50, 50), font, 1.2, (255, 255, 255), 2) # 图像,文字内容, 坐标 ,字体,大小,颜色,字体厚度
添加中文
import cv2 import numpy from PIL import Image, ImageDraw, ImageFont def cv2ImgAddText(img, text, left, top, textColor=(0, 255, 0), textSize=20): if (isinstance(img, numpy.ndarray)): # 判断是否OpenCV图片类型 img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) draw = ImageDraw.Draw(img) # 字体路径 mac下字体路径 fontText = ImageFont.truetype( "/Library/Fonts/Arial Unicode.ttf", textSize, encoding="utf-8") draw.text((left, top), text, textColor, font=fontText) return cv2.cvtColor(numpy.asarray(img), cv2.COLOR_RGB2BGR) img = cv2.imread("/tmp/2.jpg") img = cv2ImgAddText(img, "生活美好", 140, 60, (255, 255, 0), 130) cv2.imwrite("/tmp/2-2.jpg", img)
4.获取图像宽高 shape
img = cv2.imread("/tmp/h_4ddb2f3e.jpg") sp = img.shape print(sp) sz1 = sp[0] # height(rows) of image sz2 = sp[1] # width(colums) of image sz3 = sp[2] # the pixels value is made up of three primary colors print('width: %d \nheight: %d \nnumber: %d' % (sz1, sz2, sz3)) #width: 1080 height: 1080 number: 3
5.画矩形 rectangle
import numpy as np import cv2 as cv img = np.zeros((320, 320, 3), np.uint8) #生成一个空灰度图像 print img.shape # 输出:(320, 320, 3) # 矩形左上角和右上角的坐标,绘制一个绿色矩形 ptLeftTop = (60, 60) ptRightBottom = (260, 260) point_color = (0, 255, 0) # BGR thickness = 1 lineType = 4 cv.rectangle(img, ptLeftTop, ptRightBottom, point_color, thickness, lineType)
xmin = 100 xmax = 200 ymin = 100 ymax = 300 cv2.rectangle(img, (xmin, ymin), (xmax, ymax), (0,0,255), 2) cv2.rectangle(img, (xmin, ymax), (xmax, ymin), (255,0,0), 2) cv2.imshow('src',img) cv2.waitKey()
import cv2 img = cv2.imread("/tmp/abc.jpg") print(img.shape) cv2.rectangle(img, (240, 0), (480, 375), (0, 255, 0), 10) cv2.imshow("fff", img)
6.opencv实现均值模糊 均值模糊
import cv2 as cv import numpy as np def blur_demo(src): dst = cv.blur(src, (5, 5)) cv.imshow("blur_demo", dst) if __name__ == "__main__": src = cv.imread("./1.jpg") blur_demo(src) cv.waitKey() cv.destroyAllWindows()
7.获取一张图片的alpha图
import cv2 import numpy as np def img_chnl_1_to_n(img, channels=3): """ 将单通道改为三通道 :param img: :param channels: :return: """ if channels == 1: return img new_img = np.empty((img.shape[0], img.shape[1], channels)) print(new_img.shape) for c in range(channels): new_img[...,c] = img return new_img alpha = cv2.imread("/tmp/pinjie/1.png", cv2.IMREAD_UNCHANGED) alpha_ori = alpha[:,:,3] # alpha图 cv2.imwrite("/tmp/1.png",alpha_ori) alpha_ori = img_chnl_1_to_n(alpha_ori) hand_img = alpha[:,:,:3] # 三通道 cv2.imwrite("/tmp/2.png",hand_img)
8.图片缩放
import cv2 # png im1 = cv2.imread('/tmp/3.png', cv2.IMREAD_UNCHANGED) im2 = cv2.resize(im1, (200,300)) cv2.imwrite('/tmp/lena2.png', im2) cv2.imshow("original", im2) cv2.waitKey(0) #jpg # 改变图像大小 import cv2 im1 = cv2.imread(cover_path) im2 = cv2.resize(im1,(1000,550),) # 为图片重新指定尺寸 cv2.imwrite(cover_path,im2) #改变图像大小 F = cv2.imread("/tmp/p1/355.jpg") resize_img2 = cv2.resize(F,(0,0),fx = 0.5,fy = 0.5)#按比例缩放为1/2 cv2.imwrite("/tmp/p1/sf.jpg",resize_img2)
9.图片底部填充空白
""" 图片底部填充空白 """ import numpy as np import cv2 #图片宽度为640 F = cv2.imread("/tmp/123.jpg") print(F.shape) img = np.zeros((120, 640, 3), np.uint8) img.fill(000) #append添加到最后 c = np.append(F, img, axis=0) cv2.imwrite("/tmp/11111.jpg", c)
效果图
10.opencv 裁剪图片
原始图片
import cv2 img = cv2.imread("/tmp/20180903171331890.jpeg") print(img.shape) cropped = img[0:128, 0:200] # 裁剪坐标为[y0:y1, x0:x1] cv2.imwrite("/tmp/cv_cut_thor.jpg", cropped)
11.opencv+numpy np.pad向图片上下左右填充内容
import numpy as np import cv2 a = np.arange(95, 99).reshape(2, 2) # 二通道 # b = np.pad(a, ((1, 0), (0, 0)), 'constant', constant_values=0) # 向上填充0 # b = np.pad(a, ((0, 0), (0, 1)), 'constant', constant_values=0) # 向右填充0 # b = np.pad(a, ((0, 1), (0, 0)), 'constant', constant_values=0) # 向下填充0 # b = np.pad(a, ((0, 0), (1, 0)), 'constant', constant_values=0) # 向左填充0 # print(b) im = cv2.imread("/tmp/zyj.jpeg") print(im.shape) new_img = np.pad(im, ((0, 0), (50, 0), (0, 0)), 'constant', constant_values=0) # 三通道向右增加50个像素 cv2.imwrite("/tmp/zyj_new.jpg", new_img)
向左添加50个黑色像素
分类:
Python常用方法
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了