Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import cv2
- import numpy as np
- # 读取图像&将图像从 BGR 转换为 HSV
- image = cv2.imread('lab_logo.jpg')
- hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
- # 定义红色的 HSV 范围
- lower_red1 = np.array([0, 70, 50])
- upper_red1 = np.array([10, 255, 255])
- lower_red2 = np.array([170, 70, 50])
- upper_red2 = np.array([180, 255, 255])
- # 创建掩码
- mask1 = cv2.inRange(hsv, lower_red1, upper_red1)
- mask2 = cv2.inRange(hsv, lower_red2, upper_red2)
- mask = mask1 + mask2
- # 查找轮廓
- contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
- # 创建白色背景
- white_background = np.ones_like(image) * 255
- # 提取红色印章并复制在白色背景上
- for contour in contours:
- x, y, w, h = cv2.boundingRect(contour)
- if w > 10 and h > 10:
- # 提取红色印章区域
- stamp_area = image[y:y+h, x:x+w]
- mask_area = mask[y:y+h, x:x+w]
- # 创建与印章区域相同大小的白色背景
- white_bg_stamp_area = np.ones_like(stamp_area) * 255
- # 复制红色区域到白色背景上
- white_background[y:y+h, x:x+w] = np.where(mask_area[..., None], stamp_area, [255, 255, 255])
- # 保存结果
- cv2.imwrite('result_2.png', white_background)
- cv2.imshow('Result Stamp', white_background)
- cv2.waitKey(0)
- cv2.destroyAllWindows()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement