Advertisement
wyx0311

电宇智控2_2

May 31st, 2024
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.34 KB | Source Code | 0 0
  1. import cv2
  2. import numpy as np
  3.  
  4. # 读取图像&将图像从 BGR 转换为 HSV
  5. image = cv2.imread('lab_logo.jpg')
  6. hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
  7.  
  8. # 定义红色的 HSV 范围
  9. lower_red1 = np.array([0, 70, 50])
  10. upper_red1 = np.array([10, 255, 255])
  11. lower_red2 = np.array([170, 70, 50])
  12. upper_red2 = np.array([180, 255, 255])
  13.  
  14. # 创建掩码
  15. mask1 = cv2.inRange(hsv, lower_red1, upper_red1)
  16. mask2 = cv2.inRange(hsv, lower_red2, upper_red2)
  17. mask = mask1 + mask2
  18.  
  19. # 查找轮廓
  20. contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  21.  
  22. # 创建白色背景
  23. white_background = np.ones_like(image) * 255
  24.  
  25. # 提取红色印章并复制在白色背景上
  26. for contour in contours:
  27.     x, y, w, h = cv2.boundingRect(contour)
  28.     if w > 10 and h > 10:
  29.         # 提取红色印章区域
  30.         stamp_area = image[y:y+h, x:x+w]
  31.         mask_area = mask[y:y+h, x:x+w]
  32.        
  33.         # 创建与印章区域相同大小的白色背景
  34.         white_bg_stamp_area = np.ones_like(stamp_area) * 255
  35.        
  36.         # 复制红色区域到白色背景上
  37.         white_background[y:y+h, x:x+w] = np.where(mask_area[..., None], stamp_area, [255, 255, 255])
  38.  
  39. # 保存结果
  40. cv2.imwrite('result_2.png', white_background)
  41.  
  42. cv2.imshow('Result Stamp', white_background)
  43. cv2.waitKey(0)
  44. cv2.destroyAllWindows()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement