iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 3
1
Software Development

【錢不夠買ps的我,只好用OpenCV來修圖了!】系列 第 3

【沒錢ps,我用OpenCV!】Day 3 - 基本修圖2,OpenCV 圖片的剪裁、旋轉、縮放 (crop, rotate, resize),在 jupyter 中直接找尋圖片的座標

先來看看今天的結果圖

今天我們又請來了貓貓當我們助教囉~~~

https://ithelp.ithome.com.tw/upload/images/20200913/20120424ZSHWQFeftb.png

-> 此篇文章的程式碼 github

Day03_圖片剪裁旋轉縮放_crop_rotate_resize.ipynb

1. 裁減圖片

裁減圖片的方式,不需要使用 OpenCV 特別的函數,
我們只需要知道座標後,決定要裁減的範圍即可。

def crop_img(img):
    
    # left, right
    x_l, x_r = 300, 700 
    
    # up, down
    y_u, y_d = 0, 400 

    # crop image
    crop_img = img[y_u:y_d, x_l:x_r]  # notice: first y, then x
    
    return crop_img

你可能會想問,那要怎麼知道圖片的座標呢? 這也太難找了吧!
其實我們昨天就埋了一個梗在這哈哈哈哈哈,
如果昨天顯示圖片是使用在 jupyter 中直接顯示圖片的方式(透過 matplotlib),
那找座標就非常簡單了!

例如這張可愛貓貓的圖片:

https://ithelp.ithome.com.tw/upload/images/20200913/20120424epLAgzKz1C.png

我們可以大概抓一下,我抓 x=300, x=700,
至於y軸因為我想讓圖片裁剪出來為正方形 (400*400),所以我抓 y=0, y=400。

裁剪出來的效果大概就像這樣囉~

https://ithelp.ithome.com.tw/upload/images/20200913/201204244jn4eifeAM.png

2. 旋轉圖片 cv2.getRotationMatrix2D

旋轉圖片我們使用 cv2.getRotationMatrix2D 的方式。

def rotate_img(img):
    (h, w, d) = img.shape # 讀取圖片大小
    center = (w // 2, h // 2) # 找到圖片中心
    
    # 第一個參數旋轉中心,第二個參數旋轉角度(-順時針/+逆時針),第三個參數縮放比例
    M = cv2.getRotationMatrix2D(center, 15, 1.0)
    
    # 第三個參數變化後的圖片大小
    rotate_img = cv2.warpAffine(img, M, (w, h))
    
    return rotate_img

https://ithelp.ithome.com.tw/upload/images/20200913/20120424VHOicczeeT.png

3. 縮放圖片 cv2.resize

縮放圖片我們使用 cv2.resize

def resize_img(img):

    scale_percent = 50 # 要放大縮小幾%
    width = int(img.shape[1] * scale_percent / 100) # 縮放後圖片寬度
    height = int(img.shape[0] * scale_percent / 100) # 縮放後圖片高度
    dim = (width, height) # 圖片形狀 
    resize_img = cv2.resize(img, dim, interpolation = cv2.INTER_AREA)  
    
    return resize_img

https://ithelp.ithome.com.tw/upload/images/20200913/20120424fRFuHKwYyx.png

jupyter notebook 中,直接顯示的圖片結果看不出大小差異,
我們可以使用前篇文章中的 cv2.imshow
這樣就可以明顯看出圖片大小的變化。

Reference

https://www.chainnews.com/zh-hant/articles/420945635518.htm
https://blog.gtwang.org/programming/how-to-crop-an-image-in-opencv-using-python/
https://www.cnblogs.com/lfri/p/10596530.html
https://blog.csdn.net/JNingWei/article/details/78218837
https://blog.csdn.net/on2way/article/details/46801063


上一篇
【沒錢ps,我用OpenCV!】Day 2 - 基本修圖1,OpenCV 圖片的讀取、顯示、存檔 (load, show, save),附贈簡易理解「相對路徑」與「絕對路徑」
下一篇
【沒錢ps,我用OpenCV!】Day 4 - 日系濾鏡1,運用 OpenCV 調整光線 (modify brightness)
系列文
【錢不夠買ps的我,只好用OpenCV來修圖了!】30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言