Spaces:
Sleeping
Sleeping
File size: 10,008 Bytes
9f8b414 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 |
import cv2
import numpy as np
import os
# Load Haar Cascades for face and object detection
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
car_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_car.xml')
# Helper function to convert PIL to OpenCV
def pil_to_cv2(image):
return cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
# Helper function to convert OpenCV to PIL
def cv2_to_pil(image):
return cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# 1. Image and Video I/O
def image_video_io(image=None, video=None):
outputs = []
if image is not None:
img = pil_to_cv2(image)
outputs.append(cv2_to_pil(img))
if video is not None:
cap = cv2.VideoCapture(video)
ret, frame = cap.read()
if ret:
outputs.append(cv2_to_pil(frame))
cap.release()
return outputs
# 2. Color Space Conversion
def color_space_conversion(image, color_space):
img = pil_to_cv2(image)
if color_space == "HSV":
output = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
elif color_space == "LAB":
output = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
else:
output = img
return cv2_to_pil(output)
# 3. Image Resizing and Cropping
def resize_crop(image, scale, crop_x, crop_y, crop_w, crop_h):
img = pil_to_cv2(image)
h, w = img.shape[:2]
new_w, new_h = int(w * scale), int(h * scale)
resized = cv2.resize(img, (new_w, new_h))
crop_x, crop_y, crop_w, crop_h = int(crop_x * w), int(crop_y * h), int(crop_w * w), int(crop_h * h)
cropped = img[crop_y:crop_y+crop_h, crop_x:crop_x+crop_w]
return [cv2_to_pil(resized), cv2_to_pil(cropped)]
# 4. Geometric Transformations
def geometric_transform(image, angle, tx, ty):
img = pil_to_cv2(image)
h, w = img.shape[:2]
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
M[:, 2] += [tx, ty]
transformed = cv2.warpAffine(img, M, (w, h))
return cv2_to_pil(transformed)
# 5. Image Thresholding
def thresholding(image, thresh_type, thresh_value, block_size, C):
img = pil_to_cv2(image)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
if thresh_type == "Global":
_, thresh = cv2.threshold(gray, thresh_value, 255, cv2.THRESH_BINARY)
else:
thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, block_size, C)
return cv2_to_pil(thresh)
# 6. Edge Detection
def edge_detection(image, edge_type, canny_t1, canny_t2):
img = pil_to_cv2(image)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
if edge_type == "Canny":
edges = cv2.Canny(gray, canny_t1, canny_t2)
elif edge_type == "Sobel":
sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=5)
sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=5)
edges = cv2.magnitude(sobelx, sobely).astype(np.uint8)
else: # Laplacian
edges = cv2.Laplacian(gray, cv2.CV_64F).astype(np.uint8)
return cv2_to_pil(edges)
# 7. Image Filtering
def image_filtering(image, filter_type, kernel_size):
img = pil_to_cv2(image)
kernel_size = int(kernel_size) | 1
if filter_type == "Gaussian":
filtered = cv2.GaussianBlur(img, (kernel_size, kernel_size), 0)
else: # Median
filtered = cv2.medianBlur(img, kernel_size)
return cv2_to_pil(filtered)
# 8. Contour Detection
def contour_detection(image):
img = pil_to_cv2(image)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
output = img.copy()
cv2.drawContours(output, contours, -1, (0, 255, 0), 2)
return cv2_to_pil(output)
# 9. Feature Detection (ORB)
def feature_detection(image):
img = pil_to_cv2(image)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
orb = cv2.ORB_create()
keypoints, _ = orb.detectAndCompute(gray, None)
output = cv2.drawKeypoints(img, keypoints, None, color=(0, 255, 0), flags=0)
return cv2_to_pil(output)
# 10. Object Detection (Haar Cascade for cars)
def object_detection(image):
img = pil_to_cv2(image)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cars = car_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
output = img.copy()
for (x, y, w, h) in cars:
cv2.rectangle(output, (x, y), (x+w, y+h), (0, 255, 0), 2)
return cv2_to_pil(output)
# 11. Face Detection
def face_detection(image):
img = pil_to_cv2(image)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
output = img.copy()
for (x, y, w, h) in faces:
cv2.rectangle(output, (x, y), (x+w, y+h), (0, 255, 0), 2)
return cv2_to_pil(output)
# 12. Image Segmentation (GrabCut)
def image_segmentation(image):
img = pil_to_cv2(image)
mask = np.zeros(img.shape[:2], np.uint8)
bgdModel = np.zeros((1, 65), np.float64)
fgdModel = np.zeros((1, 65), np.float64)
rect = (50, 50, img.shape[1]-50, img.shape[0]-50)
cv2.grabCut(img, mask, rect, bgdModel, fgdModel, 5, cv2.GC_INIT_WITH_RECT)
mask2 = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8')
output = img * mask2[:, :, np.newaxis]
return cv2_to_pil(output)
# 13. Motion Analysis (Optical Flow)
def optical_flow(video):
cap = cv2.VideoCapture(video)
ret, frame1 = cap.read()
if not ret:
cap.release()
return None
prvs = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)
hsv = np.zeros_like(frame1)
hsv[..., 1] = 255
ret, frame2 = cap.read()
if not ret:
cap.release()
return cv2_to_pil(frame1)
next = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)
flow = cv2.calcOpticalFlowFarneback(prvs, next, None, 0.5, 3, 15, 3, 5, 1.2, 0)
mag, ang = cv2.cartToPolar(flow[..., 0], flow[..., 1])
hsv[..., 0] = ang * 180 / np.pi / 2
hsv[..., 2] = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX)
output = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
cap.release()
return cv2_to_pil(output)
# 14. Camera Calibration (Simplified)
def camera_calibration(image):
img = pil_to_cv2(image)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
chessboard_size = (9, 6)
ret, corners = cv2.findChessboardCorners(gray, chessboard_size, None)
output = img.copy()
if ret:
cv2.drawChessboardCorners(output, chessboard_size, corners, ret)
return cv2_to_pil(output)
# 15. Stereo Vision (Simplified Disparity Map)
def stereo_vision(image):
img = pil_to_cv2(image)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
stereo = cv2.StereoBM_create(numDisparities=16, blockSize=15)
disparity = stereo.compute(gray, gray) # Simplified: using same image
disparity = cv2.normalize(disparity, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8)
return cv2_to_pil(disparity)
# 16. Background Subtraction
def background_subtraction(video):
cap = cv2.VideoCapture(video)
fgbg = cv2.createBackgroundSubtractorMOG2()
ret, frame = cap.read()
if not ret:
cap.release()
return None
fgmask = fgbg.apply(frame)
output = cv2.cvtColor(fgmask, cv2.COLOR_GRAY2BGR)
cap.release()
return cv2_to_pil(output)
# 17. Image Stitching
def image_stitching(image1, image2):
img1 = pil_to_cv2(image1)
img2 = pil_to_cv2(image2)
gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
orb = cv2.ORB_create()
kp1, des1 = orb.detectAndCompute(gray1, None)
kp2, des2 = orb.detectAndCompute(gray2, None)
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
matches = bf.match(des1, des2)
matches = sorted(matches, key=lambda x: x.distance)
good_matches = matches[:10]
src_pts = np.float32([kp1[m.queryIdx].pt for m in good_matches]).reshape(-1, 1, 2)
dst_pts = np.float32([kp2[m.trainIdx].pt for m in good_matches]).reshape(-1, 1, 2)
M, _ = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
h, w = img1.shape[:2]
result = cv2.warpPerspective(img2, M, (w * 2, h))
result[0:h, 0:w] = img1
return cv2_to_pil(result)
# 18. Machine Learning (K-Means)
def kmeans_clustering(image, k):
img = pil_to_cv2(image)
Z = img.reshape((-1, 3))
Z = np.float32(Z)
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
_, label, center = cv2.kmeans(Z, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
center = np.uint8(center)
res = center[label.flatten()]
output = res.reshape(img.shape)
return cv2_to_pil(output)
# 19. Deep Learning (MobileNet SSD)
def deep_learning(image, prototxt_file, model_file):
if prototxt_file is None or model_file is None:
return None # Model files must be uploaded
img = pil_to_cv2(image)
net = cv2.dnn.readNetFromCaffe(prototxt_file.file.name, model_file.file.name)
blob = cv2.dnn.blobFromImage(cv2.resize(img, (300, 300)), 0.007843, (300, 300), 127.5)
net.setInput(blob)
detections = net.forward()
output = img.copy()
for i in range(detections.shape[2]):
confidence = detections[0, 0, i, 2]
if confidence > 0.5:
box = detections[0, 0, i, 3:7] * np.array([img.shape[1], img.shape[0], img.shape[1], img.shape[0]])
(startX, startY, endX, endY) = box.astype("int")
cv2.rectangle(output, (startX, startY), (endX, endY), (0, 255, 0), 2)
return cv2_to_pil(output)
# 20. Drawing and Text
def drawing_text(image, shape, text):
img = pil_to_cv2(image)
output = img.copy()
h, w = img.shape[:2]
if shape == "Rectangle":
cv2.rectangle(output, (50, 50), (w-50, h-50), (0, 255, 0), 2)
elif shape == "Circle":
cv2.circle(output, (w//2, h//2), 50, (0, 255, 0), 2)
cv2.putText(output, text, (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)
return cv2_to_pil(output) |