python opencv 将lena图像嵌入空白画布处
生活随笔
收集整理的這篇文章主要介紹了
python opencv 将lena图像嵌入空白画布处
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
import cv2
import matplotlib.pyplot as plt
import numpy as np
path = "./temp(1)/temp/src.jpg"
threshold = 80
讀取圖像
img = cv2.imread(path) img = img[:,:,::-1] img.shape plt.imshow(img) plt.axis('off') plt.show() # 轉化灰度 img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img_gray.shape plt.imshow(img_gray, cmap='gray') plt.axis('off') plt.show() # 高斯模糊 img_gray = cv2.GaussianBlur(img_gray, (3, 3), 1) plt.imshow(img_gray, cmap='gray') plt.axis('off') plt.show()二值轉化
_, img_br = cv2.threshold(img_gray, threshold, 255, cv2.THRESH_BINARY) plt.imshow(img_br, cmap='gray') plt.axis('off') plt.show() # 尋找外層輪廓 contours, hierarchy = cv2.findContours(img_br, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # 確保至少找到一個輪廓 contour = np.zeros((4, 2)) if len(contours) > 0:# 按輪廓大小降序排列cnts = sorted(contours, key=cv2.contourArea, reverse=True)for c in cnts:# 近似輪廓peri = cv2.arcLength(c, True)approx = cv2.approxPolyDP(c, 0.02 * peri, True)# 近似輪廓有四個點,則確定if len(approx) == 4:contour = approxbreak# 保留輪廓圖片 img_contour = img.copy() cv2.drawContours(img_contour, [contour], 0, (0, 0, 255), 1) cv2.imwrite("./contour.png",img_contour) cour = cv2.imread('./contour.png') plt.imshow(cour) plt.axis('off') plt.show() # 讀取目標圖片 dst = cv2.imread("./temp(1)/temp/dst.jpg") # dst = cv2.imread("./temp(1)/temp/7.jpg") # dst = cv2.imread('fish.jpg') plt.imshow(dst[:,:,::-1]) plt.axis('off') plt.show() # 初始化原圖Mask mask = np.zeros_like(img) # 獲取子圖長寬,賦給mask h, w, c = dst.shape mask[:h, :w, :] = 255 # mask 透射變換 # 得到變換矩陣 # 初始mask點 point1 = np.float32([[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]]) # 目標mask點 point2 = np.float32(contour.reshape(4, 2)) # 得到變換矩陣 perspective_matrix = cv2.getPerspectiveTransform(point1, point2) # 得到里白外黑mask mask_center_true = cv2.warpPerspective(mask, perspective_matrix, (img.shape[1], img.shape[0])) plt.imshow(mask_center_true) plt.axis('off') plt.show() # 取圖 mask_center_roi = cv2.bitwise_and(img,mask_center_true) plt.imshow(mask_center_roi) plt.axis('off') plt.show() # 反取mask temp = np.ones_like(img) * 255 mask_center_false = cv2.bitwise_xor(mask_center_true,temp) plt.imshow(mask_center_false) plt.axis('off') plt.show() # and src_center_false = cv2.bitwise_and(img,mask_center_false) plt.imshow(src_center_false) plt.axis('off') plt.show() # 得到dst透射變換 temp = np.zeros_like(img) temp[:h,:w,:] = dst dst_center_true = cv2.warpPerspective(temp, perspective_matrix, (img.shape[1], img.shape[0])) plt.imshow(dst_center_true[:,:,::-1]) plt.axis('off') plt.show() # 融合 result = cv2.bitwise_or(src_center_false[:,:,::-1],dst_center_true) plt.imshow(result[:,:,::-1]) plt.axis('off') plt.show()總結
以上是生活随笔為你收集整理的python opencv 将lena图像嵌入空白画布处的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 声卡驱动正常但就是没有声音,驱动人生解决
- 下一篇: 手柄xinput模式_让你的普通手柄变成