前言
從瀏覽器保存的圖片有透明度,但是python打開其透明通道是黑色的,因此我利用python的OpenCV模塊去除了其上下左右的黑邊。
效果展示
計算機中效果
python打開效果
python裁剪后效果
代碼
import cv2
def change_size(read_file):
image = cv2.imread(read_file, 1) # 讀取圖片 image_name應該是變量
img = cv2.medianBlur(image, 5) # 中值濾波,去除黑色邊際中可能含有的噪聲干擾
b = cv2.threshold(img, 15, 255, cv2.THRESH_BINARY) # 調整裁剪效果
binary_image = b[1] # 二值圖--具有三通道
binary_image = cv2.cvtColor(binary_image, cv2.COLOR_BGR2GRAY)
x = binary_image.shape[0]
print("高度x=", x)
y = binary_image.shape[1]
print("寬度y=", y)
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 = 'template.png'
template = change_size(file_names)
cv2.imshow('template', template)
cv2.waitKey(0)