opencv的图片处理:缩小尺寸为原图的一半【自己练习存档,没有参考价值,多看其他大神代码,谢谢】

【自己存档,没有参考价值,没用看其他大神代码,谢谢】
【自己存档,没有参考价值,没用看其他大神代码,谢谢】
【自己存档,没有参考价值,没用看其他大神代码,谢谢】
【自己存档,没有参考价值,没用看其他大神代码,谢谢】
【自己存档,没有参考价值,没用看其他大神代码,谢谢】

4.2 除了png转成jpg,并且jpg的长宽是原来一半这些要求外,还对文件名有要求,希望添加前缀lalala。
比如原来的图片路径是folder1/a.png,那么我们希望结果图片的路径为folder2/lalala_a.jpg
#存放原图的文件夹
input_image_path = 'D:\\Research\\Python\\Practice\\resource\\practice_4_jpg' 

#图片缩小后保存的目标文件夹
resized_image_path = r'D:\Research\Python\Practice\resource\practice_resize'


for filename in os.listdir(input_image_path):
    print(filename) #在遍历文件夹的时候,打印文件夹里所有文件的名字
    image_path = input_image_path + '\\' + filename #永远要记得加'\\'
    org_img = cv2.imread(image_path) 
    print(org_img) 

#把图片缩小为原来的一半,如果有固定尺寸,直接说cv2.resize(xxx,xxx)
    resize_image = cv2.resize(org_img, (0, 0), fx=0.5, fy=0.5, interpolation=cv2.INTER_CUBIC)

#图片的保存路径,把前缀加在原来的filename前
    resized_image = resized_image_path + '\\' + 'lalala' + filename

#保存图片cv2.imwrite
    cv2.imwrite(resized_image, resize_image)

总结:

1.不熟悉os.listdir的用法,需要巩固(看笔记或者重新多写)

os.listdir() 方法用于返回指定的文件夹包含的文件或文件夹的名字的列表。

os.listdir() method in python is used to get the list of all files and directories in the specified directory. If we don’t specify any directory, then list of files and directories in the current working directory will be returned.

2.for循环还是不熟练

3.在文件路径上一直忘记加'\\'符号

4.cv2.resize用法不熟练,之前用的是直接给出尺寸的,按比例缩小用法不一样

cv2.resize(src, dsize[, dst[, fx[, fy[, interpolation]]]])
src:[required] source/input image

dsize: [required] desired size for the output image

fx/fy:[optional] scale factor along the horizontal/vertical  axis

interpolation:[optional] flag that takes one of the following methods.通常的,缩小使用cv.INTER_AREA,放缩使用cv.INTER_CUBIC(较慢)和cv.INTER_LINEAR(较快效果也不错)。默认情况下,所有的放缩都使用cv.INTER_LINEAR。

5.保存路径resize_image的格式肯定和imge_path一样(这里文件命名不是很一致,下次可以改进)

6.cv2.imwrite的函数用法

使用函数cv2.imwrite(file,img,num)保存一个图像。 第一个参数是要保存的文件名,第二个参数是要保存的图像。 可选的第三个参数,它针对特定的格式:对于JPEG,其表示的是图像的质量,用0 - 100的整数表示,默认95;对于png ,第三个参数表示的是压缩级别,默认为3。

你可能感兴趣的:(Python练习题,opencv,人工智能,计算机视觉)