python-opencv-图像的算数运算
图像相加:
import cv2 import numpy as np image = cv2.imread("3.jpg") cv2.imshow("3",image) #图像image各像素加100 M = np.ones(image.shape,dtype="uint8")*100 #与image大小一样的全100矩阵 added = cv2.add(image,M) #两个图像相加 # 大于255的按255处理 cv2.imshow("Added",added) cv2.waitKey(0)
效果图:
图像相减:
import cv2 import numpy as np image = cv2.imread("3.jpg") cv2.imshow("yuan",image) #图像image各像素减去50 M = np.ones(image.shape,dtype="uint8")*50 #与image大小一样的全100矩阵 img = cv2.subtract(image,M) #图像image减去图像M # 小于0的按0处理 cv2.imshow("hou",img) cv2.waitKey(0)
效果图:
图像的交集运算--与运算
import numpy as np import cv2 #画矩形 Rectangle = np.zeros((300,300),dtype="uint8") cv2.rectangle(Rectangle,(25,25),(275,275),255,-1) cv2.imshow("Rectangle",Rectangle) #画圆形 Circle = np.zeros((300,300),dtype="uint8") cv2.circle(Circle,(150,150),150,255,-1) cv2.imshow("Circle",Circle) #图像的交 bitwiseAnd = cv2.bitwise_and(Rectangle,Circle) cv2.imshow("AND",bitwiseAnd) cv2.waitKey(0)
cv2.bitwise_and()是对二进制数据进行“与”操作,即对图像(灰度图像或彩色图像均可)每个像素值进行二进制“与”操作,1&1=1,1&0=0,0&1=0,0&0=0
效果图:
图像的或运算:
import numpy as np import cv2 #画矩形 Rectangle = np.zeros((300,300),dtype="uint8") cv2.rectangle(Rectangle,(25,25),(275,275),255,-1) cv2.imshow("Rectangle",Rectangle) #画圆形 Circle = np.zeros((300,300),dtype="uint8") cv2.circle(Circle,(150,150),150,255,-1) cv2.imshow("Circle",Circle) #图像的交 bitwiseAnd = cv2.bitwise_or(Rectangle,Circle) #或运算--并集 cv2.imshow("AND",bitwiseAnd) cv2.waitKey(0)
效果图:
异或运算:
import numpy as np import cv2 #画矩形 Rectangle = np.zeros((300,300),dtype="uint8") cv2.rectangle(Rectangle,(25,25),(275,275),255,-1) cv2.imshow("Rectangle",Rectangle) #画圆形 Circle = np.zeros((300,300),dtype="uint8") cv2.circle(Circle,(150,150),150,255,-1) cv2.imshow("Circle",Circle) #图像的交 bitwiseXor = cv2.bitwise_xor(Rectangle,Circle) #图像的异或 cv2.imshow("XOR",bitwiseXor) cv2.waitKey(0)
效果图:
非运算:
import numpy as np import cv2 #画圆形 Circle = np.zeros((300,300),dtype="uint8") cv2.circle(Circle,(150,150),150,255,-1) cv2.imshow("Circle",Circle) bitwiseNot = cv2.bitwise_not(Circle) #非运算 cv2.imshow("NOT",bitwiseNot) cv2.waitKey(0)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)