Opencv(Python版)-4 图像的算术运算

学习对图像的几种算术运算,如加法,减法,按位运算等。
学习以下函数:cv2.add(),cv2.addWeighted()等。
Opencv(Python版)-4 图像的算术运算_第1张图片

图像的加法运算

cv2.addWeighted(m1,w1,m2,w2),四个参数,m1 m2是两个要相加的图片,w1 w2 表示图片的显示权重,值越大图像越清晰,对比度越高。

import cv2

img1 = cv2.imread('6.png')
img2 = cv2.imread('7.png')

cv2.imshow('6',img1)
cv2.imshow('7',img2)

dst = cv2.addWeighted(img1,0.7,img2,0.3,0)

cv2.imshow('dst',dst)
cv2.waitKey(0)
cv2.destroyAllWindows()

Opencv(Python版)-4 图像的算术运算_第2张图片

图像的位运算

函数 cv2.threshold(src, thresh, maxval, type) 可对图像二值化处理,这个函数有四个参数,第一个原图像,第二个进行分类的阈值,第三个是高于(低于)阈值时赋予的新值,第四个是一个方法选择参数,常用的有:

  • cv2.THRESH_BINARY(黑白二值)
  • cv2.THRESH_BINARY_INV(黑白二值反转)
  • cv2.THRESH_TRUNC (得到的图像为多像素值)
  • cv2.THRESH_TOZERO
  • cv2.THRESH_TOZERO_INV
import cv2

# Load two images
img1 = cv2.imread('1.png')
img2 = cv2.imread('2.jpg')

# cv2.imshow('1',img1)
cv2.imshow('2',img2)

# I want to put logo on top-left corner, So I create a ROI
rows,cols,channels = img2.shape
roi = img1[0:rows, 0:cols ]

# Now create a mask of logo and create its inverse mask also
img2gray = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(img2gray,127, 1, cv2.THRESH_BINARY_INV)
cv2.imshow('3',mask)
mask_inv = cv2.bitwise_not(mask)
cv2.imshow('4',mask_inv)

# Now black-out the area of logo in ROI
img1_bg = cv2.bitwise_and(roi,roi,mask = mask_inv)
cv2.imshow('5',img1_bg)

# Take only region of logo from logo image.
img2_fg = cv2.bitwise_and(img2,img2,mask = mask)
cv2.imshow('6',img2_fg)

# Put logo in ROI and modify the main image
dst = cv2.add(img1_bg,img2_fg)
cv2.imshow('7',dst)
img1[0:rows, 0:cols ] = dst

cv2.imshow('res',img1)
cv2.waitKey(0)
cv2.destroyAllWindows()

Opencv(Python版)-4 图像的算术运算_第3张图片

ret, mask = cv2.threshold(img2gray,127, 1, cv2.THRESH_BINARY_INV) 中参数1改为255
Opencv(Python版)-4 图像的算术运算_第4张图片

简单的拼接

将小图片赋值到对应大图片的位置上

import cv2
import numpy as np

img1 = cv2.imread('1.png')
img2 = cv2.imread('2.jpg')

rows,cols,channels = img2.shape

img1[0:rows,0:cols] = img2;

cv2.imshow('res',img1)
cv2.waitKey(0)
cv2.destroyAllWindows()

Opencv(Python版)-4 图像的算术运算_第5张图片

你可能感兴趣的:(opencv,学习)