অধ্যায়Phase 2 · কোর ইমেজ প্রসেসিং
2.1 14 মিনিট পড়া

Resize, Crop, Rotate

জ্যামিতিক রূপান্তর।

🎬 গল্প দিয়ে শুরু
Instagram-এ ছবি crop করেন, Zoom-এ webcam ঘোরান, ID card স্ক্যানে কোণ ঠিক হয় — এই সবকিছুর পেছনে আছে তিনটি মৌলিক geometric operation: Resize, Crop, Rotate। Phase 2-এর প্রথম অস্ত্র এগুলোই।

Resize — ছবি ছোট-বড় করা

python
resize.py
import cv2

img = cv2.imread("dhaka.jpg")
H, W = img.shape[:2]

# পদ্ধতি ১ — fixed size
out1 = cv2.resize(img, (640, 480), interpolation=cv2.INTER_LINEAR)

# পদ্ধতি ২ — scale factor
out2 = cv2.resize(img, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA)

# পদ্ধতি ৩ — aspect ratio বজায় রেখে width fix
new_w = 800
new_h = int(H * new_w / W)
out3 = cv2.resize(img, (new_w, new_h))
লাইন-বাই-লাইন ব্যাখ্যা
(640, 480)
OpenCV size লেখে (width, height) — shape-এর উল্টো!
INTER_AREA
Downscale-এর জন্য best — moire pattern কমায়।
INTER_LINEAR/CUBIC
Upscale-এ ভালো; CUBIC ধীর কিন্তু smoother।
Aspect ratio ভাঙবেন না
fixed size দিলে ছবি stretched হতে পারে। AI model-এ feed করার আগে সাধারণত letterbox/padding দিয়ে aspect ratio বজায় রাখা হয়।

Crop — ROI কেটে নেওয়া

OpenCV-তে কোনো আলাদা crop function নেই — NumPy slicing-ই যথেষ্ট।

python
import cv2

img = cv2.imread("face.jpg")
H, W = img.shape[:2]

# মাঝখানের 300x300
cy, cx = H // 2, W // 2
roi = img[cy-150:cy+150, cx-150:cx+150]

cv2.imwrite("face_crop.jpg", roi)
Safe crop helper
সীমার বাইরে গেলে NumPy silent ভাবে ছোট array return করে। Production-এ np.clip দিয়ে coordinates clamp করুন।

Rotate — ছবি ঘোরানো

python
rotate.py
import cv2

img = cv2.imread("doc.jpg")
H, W = img.shape[:2]

# Quick — multiples of 90°
r90  = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)
r180 = cv2.rotate(img, cv2.ROTATE_180)

# Arbitrary angle via affine transform
angle = 30
M = cv2.getRotationMatrix2D((W/2, H/2), angle, scale=1.0)
rotated = cv2.warpAffine(img, M, (W, H),
                         borderValue=(0, 0, 0))
লাইন-বাই-লাইন ব্যাখ্যা
getRotationMatrix2D(center, angle, scale)
2×3 affine matrix তৈরি — rotation + scaling একসাথে।
warpAffine(img, M, (W, H))
Matrix প্রয়োগ করে নতুন ছবি; output size নিজে দিতে হয়।
borderValue
ঘোরানোর পর ফাঁকা জায়গা কোন রঙে ভরবে।

Flip ও Translate (bonus)

python
import cv2, numpy as np

img = cv2.imread("dhaka.jpg")

flip_h = cv2.flip(img, 1)   # mirror (data augmentation-এ কমন)
flip_v = cv2.flip(img, 0)

# Translate — ৫০ px ডানে, ৩০ px নিচে
M = np.float32([[1, 0, 50], [0, 1, 30]])
shifted = cv2.warpAffine(img, M, (img.shape[1], img.shape[0]))
প্র্যাকটিস টাস্ক
  1. একটি ছবির aspect ratio বজায় রেখে width=512 করুন।
  2. মুখের চারপাশে 20% padding সহ crop করার function লিখুন।
  3. ৪৫° rotate করার পর border crop না হয়ে full ছবি ধরে রাখার জন্য নতুন W,H হিসাব করে warpAffine ব্যবহার করুন।

সারসংক্ষেপ

  • cv2.resize-এ size = (W, H) — shape-এর উল্টো order।
  • Crop = NumPy slicing; আলাদা API নেই।
  • Rotate = getRotationMatrix2D + warpAffine।
  • Flip data augmentation-এর সহজ ও কার্যকর অস্ত্র।