Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
🟣 ML + AI  ·  Lesson 34

Computer Vision और OpenCV Basics

Computer vision क्या है?

Computer vision computers को images और video समझना सिखाता है: number plates पढ़ना, documents scan करना, shelf पर products गिनना, attendance के लिए चेहरे पहचानना या सड़क की दरारें जाँचना। OpenCV इसकी सबसे ज़्यादा इस्तेमाल होने वाली open-source library है, और Python में image बस pixel values का एक NumPy array है।

Terminal
pip install opencv-python matplotlib

Step 1: image एक NumPy array है

हम scikit-learn के साथ आने वाली एक असली photo इस्तेमाल करते हैं, ताकि आप बिना कुछ download किए हर उदाहरण चला सकें।

Python – image_array.py
import cv2
from sklearn.datasets import load_sample_image

rgb = load_sample_image("flower.jpg")          # NumPy array in RGB order
img = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)     # OpenCV works in BGR order
cv2.imwrite("flower.jpg", img)                 # save it like any photo

img = cv2.imread("flower.jpg")                 # how you load your own photo
print("type :", type(img).__name__, img.dtype)
print("shape:", img.shape, "→ height, width, channels")
print("pixel at row 100, col 200 (B, G, R):", img[100, 200])
print("brightest value:", img.max(), "| darkest:", img.min())
type : ndarray uint8 shape: (427, 640, 3) → height, width, channels pixel at row 100, col 200 (B, G, R): [22 22 6] brightest value: 255 | darkest: 0
⚠️ OpenCV RGB नहीं, BGR इस्तेमाल करता है

cv2.imread channels Blue-Green-Red क्रम में देता है। Matplotlib को RGB चाहिए, इसलिए दिखाने से पहले cv2.cvtColor(img, cv2.COLOR_BGR2RGB) करें, वरना लाल फूल नीले दिखेंगे।

Step 2: resize, crop, grayscale, blur

Python – basics.py
import cv2
import matplotlib.pyplot as plt
from sklearn.datasets import load_sample_image

img = cv2.cvtColor(load_sample_image("flower.jpg"), cv2.COLOR_RGB2BGR)

small = cv2.resize(img, (320, 214))                        # (width, height)
crop = img[100:330, 180:480]                               # rows, columns – plain NumPy slicing
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(img, (21, 21), 0)                  # kernel size must be odd

print("small:", small.shape, "| crop:", crop.shape, "| gray:", gray.shape)

show = [("original", img), ("crop", crop), ("grayscale", gray), ("blur", blur)]
fig, axes = plt.subplots(1, 4, figsize=(12, 2.8), dpi=100)
for ax, (title, im) in zip(axes, show):
    ax.imshow(im if im.ndim == 2 else cv2.cvtColor(im, cv2.COLOR_BGR2RGB), cmap="gray")
    ax.set_title(title); ax.axis("off")
fig.tight_layout(); fig.savefig("basics.png")
small: (214, 320, 3) | crop: (230, 300, 3) | gray: (427, 640)
Original, cropped, grayscale and blurred versions of a flower photo

Grayscale image में सिर्फ़ एक channel होता है, इसलिए उसकी shape से आख़िरी “3” हट जाता है। कई algorithms grayscale पर चलते हैं क्योंकि रंग की ज़रूरत नहीं और data तीन गुना कम होता है।

Step 3: edges और thresholding

Python – edges.py
import cv2
import matplotlib.pyplot as plt
from sklearn.datasets import load_sample_image

gray = cv2.cvtColor(load_sample_image("china.jpg"), cv2.COLOR_RGB2GRAY)

edges = cv2.Canny(gray, 100, 200)                                   # strong intensity changes
_, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)   # Otsu picks the cut-off
print("edge pixels:", int((edges > 0).sum()), "of", edges.size)

fig, axes = plt.subplots(1, 3, figsize=(12, 3.2), dpi=100)
for ax, (t, im) in zip(axes, [("grayscale", gray), ("Canny edges", edges), ("Otsu threshold", binary)]):
    ax.imshow(im, cmap="gray"); ax.set_title(t); ax.axis("off")
fig.tight_layout(); fig.savefig("edges.png")
edge pixels: 43072 of 273280
Grayscale photo, Canny edge map and Otsu black-and-white threshold
Techniqueक्या देता हैकिसमें उपयोग
Cannyजहाँ चमक अचानक बदले वहाँ पतली linesDocument borders, lane lines, shapes
Thresholdसिर्फ़ black/white imageText scan करना, objects को background से अलग करना
पहले BlurEdges/threshold से पहले noise हटाता हैPhone photos पर साफ़ नतीजे

Step 4: contours से objects गिनें

Factory का आम काम: tray पर coins (या tablets, या biscuits) गिनना। हम एक test tray बनाते हैं ताकि सही जवाब पता हो, फिर OpenCV हर object की रेखा (contour) ढूँढता है।

Python – count_coins.py
import cv2
import numpy as np

rng = np.random.default_rng(3)
tray = np.full((300, 500, 3), (60, 90, 40), np.uint8)               # green tray (BGR)
coins = [(70, 70, 32), (180, 90, 26), (300, 70, 36), (420, 100, 30),
         (100, 210, 28), (240, 210, 40), (390, 220, 25)]
for x, y, r in coins:
    cv2.circle(tray, (x, y), r, (40, 180, 220), -1)                  # golden coins
tray = cv2.add(tray, rng.integers(0, 25, tray.shape, dtype=np.uint8))  # camera noise

gray = cv2.cvtColor(tray, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5, 5), 0)
_, mask = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = [c for c in contours if cv2.contourArea(c) > 200]         # ignore tiny specks

print("coins found:", len(contours), "| actual:", len(coins))
for c in sorted(contours, key=cv2.contourArea, reverse=True)[:3]:
    (x, y), r = cv2.minEnclosingCircle(c)
    print(f"  coin at ({x:.0f}, {y:.0f}) radius ≈ {r:.0f}px")

out = tray.copy()
cv2.drawContours(out, contours, -1, (0, 0, 255), 3)
cv2.putText(out, f"{len(contours)} coins", (10, 290), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 255, 255), 2)
cv2.imwrite("counted.png", out)
coins found: 7 | actual: 7 coin at (240, 210) radius ≈ 40px coin at (300, 70) radius ≈ 36px coin at (70, 70) radius ≈ 32px
Seven coins on a tray outlined in red with the text 7 coins

Step 5: अपनी photo पर face detection

OpenCV के साथ pre-trained Haar cascade face detectors आते हैं। एक group photo को class.jpg नाम से इस script के पास save करके चलाएँ। यह सिर्फ़ चेहरे ढूँढता है – यह नहीं जानता कि वे कौन हैं।

Python – detect_faces.py (use your own photo)
import cv2

detector = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
img = cv2.imread("class.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = detector.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(40, 40))
print("faces found:", len(faces))
for (x, y, w, h) in faces:
    cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.imwrite("class_faces.jpg", img)
🔐 Privacy

लोगों की photos personal data हैं। अपनी photos इस्तेमाल करें या अनुमति लें, दूसरों के चेहरे online tools पर कभी upload न करें, और attendance systems के लिए school या company के नियम मानें।

Haar cascades तेज़ पर पुराने हैं। आधुनिक projects deep-learning detectors (OpenCV का DNN module, MediaPipe, YOLO) इस्तेमाल करते हैं, जो तिरछे चेहरे और कम रोशनी बहुत बेहतर संभालते हैं।

Loop में webcam video

Python – webcam_edges.py (run on your computer)
import cv2

cap = cv2.VideoCapture(0)                  # 0 = default webcam
while True:
    ok, frame = cap.read()
    if not ok:
        break
    edges = cv2.Canny(cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY), 80, 160)
    cv2.imshow("edges – press q to quit", edges)
    if cv2.waitKey(1) & 0xFF == ord("q"):
        break
cap.release()
cv2.destroyAllWindows()

Video बस प्रति सेकंड कई images है; ऊपर की हर technique frame-by-frame काम करती है।

Project ideas

ProjectTechniques
Document scanner (page crop और सीधा करना)Canny, contours, perspective transform
Production line के लिए tablet/biscuit counterThreshold, contours, area filter
रंग से object tracker (गेंद)HSV colour mask, contours, video loop
Attendance helper (सहमति के साथ)Face detection + recognition model

Photo credits

scikit-learn के साथ आने वाली sample photos: Flickr पर vultilion की flower.jpg और danielbuechele की china.jpg, licence CC BY 2.0। ऊपर के बदले हुए रूप इसी page के code से बने हैं।

अभ्यास

  1. अपनी photo load करके shape छापें और grayscale copy save करें।
  2. Canny thresholds को (50, 150) और (150, 250) करके तुलना करें।
  3. Step 4 में दो छूते हुए coins जोड़कर देखें गिनती का क्या होता है – फिर अलग करने के लिए cv2.erode आज़माएँ।
  4. HSV image पर cv2.inRange से सिर्फ़ लाल pixels का mask बनाएँ।

सारांश

  • Images NumPy arrays हैं: (height, width, channels); OpenCV BGR इस्तेमाल करता है।
  • Slicing से crop, cv2.resize से resize, cv2.cvtColor से convert।
  • Blur → threshold/Canny → contours objects ढूँढने और गिनने की classic pipeline है।
  • Haar cascades चेहरे जल्दी ढूँढते हैं; deep-learning detectors ज़्यादा सटीक हैं।
  • लोगों की photos को निजी data मानें।

अक्सर पूछे जाने वाले प्रश्न (FAQ)

opencv-python और opencv-contrib-python में क्या अंतर है?
opencv-python में मुख्य modules हैं। opencv-contrib-python extra, कभी-कभी experimental modules जोड़ता है (जैसे कुछ feature detectors और face recognisers)। एक venv में इनमें से सिर्फ़ एक install करें।
क्या computer vision के लिए deep learning ज़रूरी है?
हमेशा नहीं। सादे background पर objects गिनना, documents scan करना और रंग से tracking classic OpenCV से अच्छे चलते हैं। अव्यवस्थित असली photos में कई तरह के objects पहचानने के लिए YOLO जैसे deep learning models चाहिए।
← Back to Python Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 लाइव कोड एडिटर

इस पेज के प्रोग्राम यहीं तैयार हैं — चलाएँ, बदलें और सीखें। कुछ भी इंस्टॉल किए बिना।
OneCompiler द्वारा संचालित। कोड एडिटर में अपने आप आ जाता है — Run दबाकर आउटपुट देखें। अगर एडिटर न खुले तो नए टैब में खोलें.
अगला topicGenerative AI और LLM Basics आपकी प्रगति: 34 / 66 (52%) · Lesson 35 / 66 आगे बढ़ें →

यह lesson कैसा लगा?

आपकी राय से हम content और बेहतर बनाते हैं।

अपना review और सुझाव लिखें (वैकल्पिक)

Review approve होने के बाद आपका नाम और शहर इसके साथ public दिख सकते हैं। Email या phone न लिखें।

▶ CodingEasily on YouTube

Video से सीखें – आसान Hindi में

चुनी हुई video: RDBMS भाग 3 – Class XI Commerce IT

▶ Channel subscribe करें