python3 扶正图像封闭区域 / png转jpg
from imutils import perspective
from skimage.filters import threshold_local
import cv2, sys
import imutils
# 边缘扫描
input = "test_imutils.png"
if len(sys.argv)>1 and len(sys.argv[1])>0:
input = sys.argv[1]
image = cv2.imread(input)
ratio = image.shape[0] / 500.0# 比例
orig = image.copy()
image = imutils.resize(image, height = 500)
# 灰度转换及边缘查找
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (5, 5), 0)
edged = cv2.Canny(gray, 75, 200) # 边缘检测
cv2.imshow("image", edged)
cv2.waitKey(0)
# 只保留轮廓
cnts = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)#通过边缘图像找到轮廓
cnts = cnts[0] if imutils.is_cv2() or imutils.is_cv4() else cnts[1]
# 用以区分OpenCV2.4/和OpenCV3
cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5] # 保留最大轮廓, 面积参数排序
for c in cnts:
peri = cv2.arcLength(c, True) # 轮廓周长
approx = cv2.approxPolyDP(c, 0.02 * peri, True) # 轮廓点, 闭合多边形
if len(approx) == 4: # 表明找到四个轮廓点
screenCnt = approx
break
# 转为鸟瞰图
warped = perspective.four_point_transform(orig, screenCnt.reshape(4, 2) * ratio)
cv2.imshow("OK", imutils.resize(warped))
#cv2.imwrite('warped_'+input,imutils.resize(warped),[int(cv2.IMWRITE_JPEG_QUALITY),100])
print("new filename: ", "warped_"+input[2:])
cv2.imwrite("warped_"+input[2:],imutils.resize(warped))
warped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY) # 灰度转换
T = threshold_local(warped, 11, offset = 10, method = "gaussian")
warped = (warped > T).astype("uint8") * 255
cv2.imshow("Original", imutils.resize(orig, height = 650))
cv2.imshow("Scanned", imutils.resize(warped, height = 650))
cv2.waitKey(0)
https://zhuanlan.zhihu.com/p/61328775
http://www.pointborn.com/article/2021/5/17/1378.html
png -> jpg
import os,cv2
path = "D:\\xxx\\yyy\\"
for _f in os.listdir(path):
if os.path.splitext(_f)[1] == '.png':
img = cv2.imread(path + _f)
_newF = _f.replace(".png",".jpg")
print(_newF)
cv2.imwrite(path + _newF, img)
浙公网安备 33010602011771号