php智能裁剪黑边,图片裁剪去除黑边

前言

从浏览器保存的图片有透明度,但是python打开其透明通道是黑色的,因此我利用python的OpenCV模块去除了其上下左右的黑边。

效果展示

01922e334a8a

计算机中效果

01922e334a8a

python打开效果

01922e334a8a

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值