图片裁剪:

from selenium import webdriver
import time
import random
#导入PIL模块和Image:
from PIL import Image
#导入expected_conditions预期包判断标题是否正确:
from selenium.webdriver.support import expected_conditions as EC
#导入WebDriverWait
from selenium.webdriver.support.wait import WebDriverWait
#导入by:
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.maximize_window()
driver.get("http://www.5itest.cn/register")
#操作滚轮滑动到底部:
# driver.execute_script("window.scrollTo(0,document.body.scrollHeight);")
#保存整个页面的图片用save_screenshot:
driver.save_screenshot("C:/我的代码/selenium自动化测试/Selenium3 与 Python3 实战 Web自动化测试框架/imooc.png")
#获取定位验证码图片元素的id:
code_element = driver.find_element_by_id("getcode_num")
#拿到图片的坐标值用location:
print(code_element.location) #结果是:{"x":123,"y":345}
#拿到左边x的值:
left = code_element.location["x"]
#拿到右边y的值:
top = code_element.location["y"]
#通过size拿到图片的宽度和高度:
right = code_element.size["width"] + left
height = code_element.size["height"] + top
#打开图片:
# im = Image.open("C:/我的代码/selenium自动化测试/Selenium3 与 Python3 实战 Web自动化测试框架/imooc.png")
#按照一定坐标裁剪图片用crop:
# img = im.crop((left,top,right,height))
#保存图片为imooc1.png:
# img.save("C:/我的代码/selenium自动化测试/Selenium3 与 Python3 实战 Web自动化测试框架/imooc1.png")
from PIL import Image
image = Image.open("C:/我的代码/selenium自动化测试/Selenium3 与 Python3 实战 Web自动化测试框架/imooc.png")
cropped_image = image.crop((left,top,right,height))
cropped_image.save("C:/我的代码/selenium自动化测试/Selenium3 与 Python3 实战 Web自动化测试框架/imooc1.png")
from PIL import Image
image = Image.open("C:/我的代码/selenium自动化测试/Selenium3 与 Python3 实战 Web自动化测试框架/imooc1.png").convert("L")
cropped_image = image.crop((0,0,45,50))
cropped_image.save("cropped_image.png")

#图像去杂、清理干扰因子:
pixel_matrix = cropped_image.load()
for col in range(0,cropped_image.height):
for row in range(0,cropped_image.width):
if pixel_matrix[row,col] != 0:
pixel_matrix[row,col] = 255
image.save("thresholded_image.png")

#去除图像中的黑点:
for column in range(1,image.height - 1):
for row in range(1,image.width - 1):
if pixel_matrix[row,column] == 0 and pixel_matrix[row,column - 1] == 10 and pixel_matrix[row,column + 1] == 10:
pixel_matrix[row,column] = 255
if pixel_matrix[row,column] == 0 and pixel_matrix[row - 1,column] == 255 and pixel_matrix[row + 1,column] == 255:
pixel_matrix[row,column] = 255

你可能感兴趣的:(图片裁剪:)