get_mask_by_green.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. from .generate_main_image.image_deal_base_func import *
  2. class GetMask(object):
  3. def __init__(self):
  4. pass
  5. def find_green_areas(self, cv2_jpg):
  6. # pp_jpg = PictureProcessing(image_path)
  7. # pp_jpg = pp_jpg.resize(value=800)
  8. # cv2_jpg = pil_to_cv2(pp_jpg.im)
  9. # 将图像从BGR格式转换为HSV格式
  10. hsv_image = cv2.cvtColor(cv2_jpg, cv2.COLOR_BGR2HSV)
  11. # 定义绿色范围
  12. lower_green = np.array([35, 43, 46])
  13. upper_green = np.array([77, 255, 255])
  14. # 根据颜色范围创建掩膜
  15. mask = cv2.inRange(hsv_image, lower_green, upper_green)
  16. # 查找轮廓
  17. contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  18. # 创建空白图像用于绘制符合条件的区域
  19. green_areas_mask = np.zeros_like(mask)
  20. for contour in contours:
  21. area = cv2.contourArea(contour)
  22. if area > 100: # 只选择面积大于100的区域
  23. cv2.drawContours(green_areas_mask, [contour], -1, 255, -1)
  24. # 转换为PIL图像
  25. green_areas_mask_pil = Image.fromarray(green_areas_mask)
  26. # pp_bg = PictureProcessing("RGB", pp_jpg.size, (255, 255, 255))
  27. # bg_im = pp_bg.im
  28. # bg_im.paste(pp_jpg.im, mask=green_areas_mask_pil)
  29. return green_areas_mask_pil
  30. if __name__ == '__main__':
  31. image_path = r"D:\MyDocuments\PythonCode\MyPython\red_dragonfly\deal_pics\auto_capture_V2\auto_photo\output\测试阴影\1\MD251202_6951(1).jpg"
  32. # 使用函数并传入图片路径
  33. mask_image = GetMask().find_green_areas(image_path)
  34. mask_image.show() # 显示结果