OpenCV (4.1.1)
1、讀取和保存圖片
import numpy as np
import cv2
from matplotlib import pyplot as plt
# img = cv2.imread("test.jpg",0) # 灰度圖
img = cv2.imread("opencv_test_picture/read.jpg")
# cv2.imshow('image',img) 顯示不出來
# plt.imshow(img)
plt.imshow(img, cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis
plt.show()
cv2.imwrite("opencv_test_picture/write.jpg", img)
print(img.shape)
print(img.size) # 返回圖像的像素數目
print(img.dtype)# 圖像的數據類型
2、添加logo
# encoding: utf-8
"""
@author: sunxianpeng
@file: operation.py
@time: 2019/10/25 15:22
"""
import numpy as np
import cv2
from matplotlib import pyplot as plt
class Main():
def __init__(self):
pass
def read_pic(self,path):
# img = cv2.imread("test.jpg",0) # 灰度圖
img = cv2.imread(path)
return img
def show_pic(self,img):
# cv2.imshow('image',img) 顯示不出來
# plt.imshow(img)
plt.imshow(img, cmap='gray', interpolation='bicubic')
# plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis
plt.show()
def write_pic(self,img, path):
cv2.imwrite(path, img)
def add_logo(self):
# 加載圖像
img1 = m.read_pic(path1)
img2 = m.read_pic(path2)
# 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, 175, 255, cv2.THRESH_BINARY)
mask_inv = cv2.bitwise_not(mask)
# Now black-out the area of logo in ROI
# 取 roi 中與 mask 中不爲零的值對應的像素的值,其他值爲 0
# 注意這裏必須有 mask=mask 或者 mask=mask_inv, 其中的 mask= 不能忽略
print(roi.dtype)
print(mask.dtype)
print(mask.shape)
print(roi.shape)
img1_bg = cv2.bitwise_and(roi, roi, mask=mask)
# img1_bg = cv2.bitwise_and(roi, roi)
# # 取 roi 中與 mask_inv 中不爲零的值對應的像素的值,其他值爲 0。
# # Take only region of logo from logo image.
img2_fg = cv2.bitwise_and(img2, img2, mask=mask_inv)
# img2_fg = cv2.bitwise_and(img2, img2)
# # Put logo in ROI and modify the main image
dst = cv2.add(img1_bg, img2_fg)
img1[0:rows, 0:cols] = dst
m.show_pic(img1)
if __name__ == '__main__':
m = Main()
path1 = r"F:\PythonProjects\python_study\xiaohulu\image_process\data\ball.jpg"
path2 = r"F:\PythonProjects\python_study\xiaohulu\image_process\data\opencv_logo3.jpg"
m.add_logo()
問題
error: OpenCV(4.1.1) /io/opencv/modules/core/src/arithm.cpp:663: error: (-209:Sizes of input arguments do not match) The operation is neither 'array op array' (where arrays have the same size and the same number of channels), nor 'array op scalar', nor 'scalar op array' in function 'arithm_op'
解決辦法:
logo圖片的行和列數必須小於非logo圖片
1、查看圖像大小是否一致
2、查看圖像數據類型是否一致(.dtype查看出具類型。uint8等類型是否一致)
3、查看mask圖像是否符合要求(需灰度模式圖像)