首页 > 代码库 > Python OpenCV —— bitwise

Python OpenCV —— bitwise

  关于图像的位操作,目的是为了将一个logo覆盖到另一个图片上。

# -*- coding: utf-8 -*-"""Created on Wed Sep 28 20:05:50 2016@author: Administrator"""‘‘‘位运算Bitwise Operations‘‘‘import numpy as npimport cv2def show(img_name,img_data):	cv2.imshow(img_name,img_data)	cv2.waitKey(0)	cv2.destroyAllWindows()# Load two imagesimg1 = cv2.imread(‘ml.png‘)img2 = cv2.imread(‘opencv_logo.png‘)# I want to put ligo on top-left corner,so I create a ROIrows,cols,channels = img2.shaperoi = img1[0:rows,0:cols]#show(‘roi‘,roi)# Now create a mask of logo and create its inverse mask alsoimg2gray = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY)#show(‘img2gray‘,img2gray)# threshold 阀值函数# grayscale image; threshold; maxval; function of style# THRESH_BINARY ret, mask = cv2.threshold(img2gray,10,255,cv2.THRESH_BINARY)#show(‘mask‘,mask)mask_inv = cv2.bitwise_not(mask)#show(‘mask_inv‘,mask_inv)# Now black-out the area of logo in ROI# sr1;sr2;dst;mask;# dst 就是记录结果的 mask 就是控制位# 就是 2个数据都要先和mask按位和 然后再按位和 如果有mask这个参数的话# 通过位的与运算,达到“掩盖”的目的img1_bg = cv2.bitwise_and(roi,roi,mask = mask_inv)#show(‘img1_bg‘,img1_bg)# Take only region of logo from logo imageimg2_fg = cv2.bitwise_and(img2,img2,mask=mask)#show(‘img2_fg‘,img2_fg)# Put logo in ROI and modify the main imagedst = cv2.add(img1_bg,img2_fg)show(‘dst‘,dst)img1[0:rows,0:cols] = dstshow(‘res‘,img1)

  输出图形(位置好像不太对。。。请忽略):

技术分享

  这里感谢交流群里废帝和黄同学帮助理解位运算。目前还是不能深入理解,再学习下吧。

Python OpenCV —— bitwise