selenium打开并保存图片

cooolr 于 2022-09-21 发布
  1. 全屏打开图片

     driver.maximize_window()
    
  2. 截图

     driver.save_screenshot("test.jpg")
    
  3. opencv裁掉黑边

     import cv2
        
     def change_size(read_file):
         # 读取图片 默认参数 1,加载彩色,忽略透明
         image = cv2.imread(read_file, 1)
         # 中值滤波,去除黑色边际中可能含有的噪声干扰
         img = cv2.medianBlur(image, 5)
         # 二值化,具有RGB三通道
         _,binary_image = cv2.threshold(img, 15, 255, cv2.THRESH_BINARY)
         # 颜色空间转换,转为单通道的灰度图像
         binary_image = cv2.cvtColor(binary_image, cv2.COLOR_BGR2GRAY)
         # 获取宽高
         x, y = binary_image.shape
         # 记录黑色像素坐标点
         edges_x = []
         edges_y = []
         for i in range(x):
             for j in range(y):
                 if binary_image[i][j] == 255:
                     edges_x.append(i)
                     edges_y.append(j)
         # 获取上、下、左、右边界坐标和宽高度
         left = min(edges_x)  # 左边界
         right = max(edges_x)  # 右边界
         width = right - left  # 宽度
         bottom = min(edges_y)  # 底部
         top = max(edges_y)  # 顶部
         height = top - bottom  # 高度
         # 图片截取
         pre1_picture = image[left:left + width, bottom:bottom + height]
         # 返回图片数据
         return pre1_picture
        
     if __name__ == '__main__':
         file_names = 'test.jpg'
         template = change_size(file_names)
         cv2.imwrite("test2.jpg", template)
    

参考链接: