一、
from PIL import Image
import os.path
import glob
def convertjpg(inputpath, outpath, width, height):
img = Image.open(inputpath)
new_img = img.resize((width, height), Image.BILINEAR)
new_img.save(outpath)
inputpath = r''
outpath = r''
for img in glob.glob(r"inputpath/*.jpg"):
convertjpg(img, outpath, 256, 256)
效果很差
二、
import cv2
def process_image(img, min_side):
size = img.shape
h, w = size[0], size[1]
#长边缩放为min_side
scale = max(w, h) / float(min_side)
new_w, new_h = int(w/scale), int(h/scale)
resize_img = cv2.resize(img, (new_w, new_h))
# 填充至min_side * min_side
if new_w % 2 != 0 and new_h % 2 == 0:
top, bottom, left, right = (min_side-new_h)/2, (min_side-new_h)/2, (min_side-new_w)/2 + 1, (min_side-new_w)/2
elif new_h % 2 != 0 and new_w % 2 == 0:
top, bottom, left, right = (min_side-new_h)/2 + 1, (min_side-new_h)/2, (min_side-new_w)/2, (min_side-new_w)/2
elif new_h % 2 == 0 and new_w % 2 == 0:
top, bottom, left, right = (min_side-new_h)/2, (min_side-new_h)/2, (min_side-new_w)/2, (min_side-new_w)/2
else:
top, bottom, left, right = (min_side-new_h)/2 + 1, (min_side-new_h)/2, (min_side-new_w)/2 + 1, (min_side-new_w)/2
pad_img = cv2.copyMakeBorder(resize_img, int(top), int(bottom), int(left), int(right), cv2.BORDER_CONSTANT, value=[0,0,0]) #从图像边界向上,下,左,右扩的像素数目
return pad_img
if __name__ == '__main__':
path = r''
image = cv2.imread(path)
print(type(image))
img_new = process_image(image, 256)
cv2.imshow("img_new", img_new)
cv2.waitKey()
copyMakeBorder
函数原型
void copyMakeBorder( const Mat& src, Mat& dst,
int top, int bottom, int left, int right,
int borderType, const Scalar& value=Scalar() );
功能
扩充src边缘,将图像变大,便于处理边界,该函数调用了cv::borderInterpolate
其中:
src,dst:原图与目标图像
top,bottom,left,right分别表示在原图四周扩充边缘的大小
borderType:扩充边缘的类型,OpenCV中给出以下几种方式
- BORDER_REPLICATE
- BORDER_REFLECT
- BORDER_REFLECT_101
- BORDER_WRAP
- BORDER_CONSTANT
Various border types, image boundaries are denoted with ‘|’
- BORDER_REPLICATE: aaaaaa|abcdefgh|hhhhhhh
- BORDER_REFLECT: fedcba|abcdefgh|hgfedcb
- BORDER_REFLECT_101: gfedcb|abcdefgh|gfedcba
- BORDER_WRAP: cdefgh|abcdefgh|abcdefg
- BORDER_CONSTANT: iiiiii|abcdefgh|iiiiiii with some specified ‘i’
BORDER_REPLICATE:复制法,也就是复制最边缘像素。
BORDER_REFLECT_101:对称法,也就是以最边缘像素为轴,对称。(默认)
BORDER_CONSTANT:常量法。常量法就是以一个常量像素值(由参数 value给定)填充扩充的边界值
三、
import tensorflow as tf
import numpy as np
import cv2
#获取图像的基本
path = r''
img = cv2.imread(path, 1)
imgInfo = img.shape
height = imgInfo[0]
width =imgInfo[1]
dstHeight = int(height/4)
dstWidth = int(width/4)
#创建空白模板,其中np.uint8代表图片的数据类型0-255
dstImage = np.zeros((dstHeight, dstWidth, 3), np.uint8)
#对新的图像坐标进行重新计算,对矩阵进行行列遍历
for i in range(0, dstHeight):
for j in range(0, dstWidth):
iNew = int(i*(height*1.0 / dstHeight))
jNew = int(j*(width*1.0/dstWidth))
dstImage[i, j] = img[iNew, jNew]
path2 = r''
cv2.imwrite(path2, dstImage)
cv2.imshow('new_img', dstImage)
cv2.waitKey(0)
二和三的效果是差不多的,但是图片也会失真,这是不可避免的