OpenCV-15位运算

OpenCV中的逻辑运算就是对应位置的元素进行与、或、非和异或。

Opencv与Python不同的是:OpenCV中0的非反过来是255,255反过来是0。

但是Python中255非为-256。

一、非运算

使用API---cv.bitwise_not(str)

示例代码如下:

import cv2
import numpy as np


cat = cv2.imread("cat.png")


cat_not = cv2.bitwise_not(cat)      # 进行非运算
cv2.imshow("not", np.hstack((cat, cat_not)))   # 两张图片水平展示
print(cat[:2, :2])
print(cat_not[:2, :2])

cv2.waitKey(0)
cv2.destroyAllWindows()

输出结果如下:

从图片中我们可以发现:猫白色的部分变为了黑色.

从数组中我们可以看出:每个数字取反,在munpy中最大值为255,因此此时255-90=165。

二、与运算 

使用API---cv.bitwise_and(str)

 

第一个为小狗,第二个为小猫,第三个为经过与运算的,其中246 & 90 = 82

OpenCV与Python中的与运算一致,都是先将十进制数字转为二进制,再进行与运算,最后再转化为十进制。

且一般经过与运算后的数字比前两个较小。

三、或运算

使用API---cv.bitwise_or(str)

 

与对应位置元素进行或运算 

其中 246 | 90 = 254,或运算的法则与Python一样。

整体数字变大,图片变亮。

四、异或运算

使用API---cv.bitwise_xor(str)

注意点:np.hstack(),中间补充的元素必须为元组。

 

整体颜色比较乱。按对应位置的元素进行二进制异或操作。

数字相同为1,数字不同为0.

经验证可得 246 ^ 90  = 172     其中255 ^255 = 0

综合演示代码如下所示:

import cv2
import numpy as np


cat = cv2.imread("cat.png")
dog = cv2.imread("dog.png")
new_dog = dog[:370, :550]
new_cat = cat[:370, :550]

# cat_not = cv2.bitwise_not(cat)      # 进行非运算
# cv2.imshow("not", np.hstack((cat, cat_not)))   # 非运算两张图片水平展示

# cat_and = cv2.bitwise_and(new_cat, new_dog)
# cv2.imshow("and", np.hstack((new_cat, cat_and)))   # 与运算两张图片水平展示

# cat_or = cv2.bitwise_or(new_cat, new_dog)
# cv2.imshow("or", np.hstack((new_cat, cat_or)))   # 与运算两张图片水平展示

cat_xor = cv2.bitwise_xor(new_cat, new_dog)
cv2.imshow("xor", np.hstack((new_cat, cat_xor)))
print(new_dog[:2, :2])
print("-----------------------")
print(new_cat[:2, :2])
print("-----------------------")
# print(cat_and[:2, :2])    # 输出两个图片的与操作
# print(cat_or[:2, :2])    # 输出两个图片的或操作
print(cat_xor[:2, :2])    # 输出两个图片的或操作


cv2.waitKey(0)
cv2.destroyAllWindows()

 

相关推荐

  1. OpenCV图像算术运算

    2024-01-08 09:00:02       33 阅读
  2. Python系列(17)—— 运算符

    2024-01-08 09:00:02       45 阅读
  3. <span style='color:red;'>位</span><span style='color:red;'>运算</span>

    运算

    2024-01-08 09:00:02      36 阅读
  4. 【玩转python】入门篇day11-运算

    2024-01-08 09:00:02       24 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-08 09:00:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-08 09:00:02       106 阅读
  3. 在Django里面运行非项目文件

    2024-01-08 09:00:02       87 阅读
  4. Python语言-面向对象

    2024-01-08 09:00:02       96 阅读

热门阅读

  1. python笔记-自用

    2024-01-08 09:00:02       57 阅读
  2. React07-路由管理器react-router

    2024-01-08 09:00:02       49 阅读
  3. MySQL第一讲:MySQL知识体系详解(P6精通)

    2024-01-08 09:00:02       54 阅读
  4. 企业云安全能力建设的要点

    2024-01-08 09:00:02       54 阅读
  5. es6中箭头函数 原型

    2024-01-08 09:00:02       56 阅读
  6. shtml与html的区别

    2024-01-08 09:00:02       53 阅读
  7. oracle xml_data 包的使用

    2024-01-08 09:00:02       60 阅读
  8. 【面试】Redis基础知识

    2024-01-08 09:00:02       57 阅读