Python實驗五-圖像操作

圖像操作

#!/usr/bin/python3
# -*- coding:UTF-8 -*-
#
# import subprocess;
# import time;
# 【執行指定的程序】
# cal = subprocess.Popen('c:\\Windows\\System32\\calc.exe');
# #可以傳遞列表參數:['C:\\Windows\\notepad.exe', 'C:\\hello.txt'];同時打開兩個程序
# cal.poll();
# cal.wait();#等待,並終止程序
# cal.poll();#等待,並終止程序【配合使用】

from PIL import ImageColor;
from PIL import Image;

rbg_1 = ImageColor.getcolor('red', 'RGBA');
# print(rbg_1);
# 【操作圖像】
catIm = Image.open('E:\\test_1.png');
print(catIm.size);  # 輸出圖像的尺寸
width, height = catIm.size;  # 給寬和高進行賦值
print(width);
print(catIm.filename);  # 輸出圖像名稱:test.png
print(catIm.format);  # 輸出原始圖像後綴名:PNG(重命名的,無用)
print(catIm.format_description);  # 輸出圖像原始屬性
catIm.save('E:\\test_dir\\2.png');  # 重新命名

# 【創建一個新的圖像】
im = Image.new('RGBA', (100, 200), 'purple');
im.save('E:\\test_dir\\3.png');

# 【裁剪圖像】
new_crop = catIm.crop((50, 50, 150, 150));
new_crop.save('E:\\test_dir\\new_cop.png');  # 生成一個100px X 100px的新文件

# 【複製和粘貼圖像到其他圖像】
newIt = Image.open('E:\\test_1.png');  # 父本圖像
newCat = newIt.copy();
newCat.paste(new_crop, (0, 0));  # 父本圖像中傳入子本圖像對象
newCat.save('E:\\test_dir\\new_cop_copy.png')

# 【調整圖像尺寸】
quar = catIm.resize((100, 3000));  # 調整:寬,高
quar.save('E:\\test_dir\\new_cop_copy_quar.png');

# 【旋轉圖像】
catIm.rotate(90).save('E:\\test_dir\\new_cop_copy_quar_route.png');  # 旋轉90度
# 如果設置expand=True,就會放大圖像的尺寸,以適應整個旋轉後的新圖像;
catIm.rotate(90, expand=True).save('E:\\test_dir\\new_cop_copy_quar_route——90.png');  # 旋轉90度

# 【鏡像旋轉】
# 水平圖像鏡像翻轉
catIm.transpose(Image.FLIP_LEFT_RIGHT).save('E:\\test_dir\\new_cop_copy_quar_route_Right.png');
# 垂直鏡像翻轉
catIm.transpose(Image.FLIP_TOP_BOTTOM).save('E:\\test_dir\\new_cop_copy_quar_route_Veri.png');

# 【創建圖像上下分層的技巧:即更改單個元素】
im = Image.new('RGBA', (100, 100))
im.getpixel((0, 0))
# 處理上半層的值
for x in range(100):
    for y in range(50):
        im.putpixel((x, y), (210, 210, 210))
# 處理下半層的值
for x in range(100):
    for y in range(50, 100):
        # ImageColor.getcolor('darkgray', 'RGBA') 獲取顏色值(255,0,255)
        im.putpixel((x, y), ImageColor.getcolor('darkgray', 'RGBA'));

# im.getpixel((0, 0)) 生成某個點的座標值的座標顏色值
# im.getpixel((0, 50))

im.save('putPixel.png')

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章