def toGrayscale(img): newimg=cv.fromarray(img) newConvertedImage = cv.CreateImage ((50, 50), cv.IPL_DEPTH_8U, 1) cv.cvtColor(newimg,newConvertedImage,cv.CV_BGR2GRAY) import imgutil newimg=imgutil.cv2array(newConvertedImage) return newimg
def detectObject(image): size = cv.GetSize(image) grayscale = cv.CreateImage(size, 8, 1) cv.cvtColor(image, grayscale, cv.CV_BGR2GRAY) storage = cv.CreateMemStorage(0) cv.EqualizeHist(grayscale, grayscale) cascade = cv.Load("haarcascade_frontalface_alt.xml") faces = cv.HarrDetectObjects(grayscale, cascade, storage, 1.2, 2 cv.CV_HAAR_DO_CANNY_PRUNING, (100, 100)) for i in faces: ((x, y, w, h), d) = i cv.Rectangle(image, (int(x), int(y)), (int(x+w), int(y+h)), cv.CV_RGB(0, 255, 0), 3, 8, 0)
def main(argv): default_file = 'images/board.JPEG' filename = argv[0] if len(argv) > 0 else default_file # Loads an image src = cv.imread(cv.samples.findFile(filename), cv.IMREAD_GRAYSCALE) # Check if image is loaded fine if src is None: print('Error opening image!') print('Usage: hough_lines.py [image_name -- default ' + default_file + '] \n') return -1 dst = cv.Canny(src, 50, 200, None, 3) # Copy edges to the images that will display the results in BGR cdst = cv.cvtColor(dst, cv.COLOR_GRAY2BGR) cdstP = np.copy(cdst) lines = cv.HoughLines(dst, 1, np.pi / 180, 150, None, 0, 0) if lines is not None: for i in range(0, len(lines)): rho = lines[i][0][0] theta = lines[i][0][1] a = math.cos(theta) b = math.sin(theta) x0 = a * rho y0 = b * rho pt1 = (int(x0 + 1000 * (-b)), int(y0 + 1000 * (a))) pt2 = (int(x0 - 1000 * (-b)), int(y0 - 1000 * (a))) cv.line(cdst, pt1, pt2, (0, 0, 255), 3, cv.LINE_AA) linesP = cv.HoughLinesP(dst, 1, np.pi / 180, 50, None, 50, 10) if linesP is not None: for i in range(0, len(linesP)): l = linesP[i][0] cv.line(cdstP, (l[0], l[1]), (l[2], l[3]), (0, 0, 255), 3, cv.LINE_AA) y = int(round(1536 / 3)) x = int(round(2048 / 3)) src = cv.resize(cdst, (x, y)) # Resize image cdst = cv.resize(cdst, (x, y)) # Resize image cdstP = cv.resize(cdstP, (x, y)) # Resize image cv.imshow("Source", src) cv.imshow("Detected Lines (in red) - Standard Hough Line Transform", cdst) cv.imshow("Detected Lines (in red) - Probabilistic Line Transform", cdstP) cv.imwrite("./houghLines.png", cdstP) cv.waitKey() return 0
def display_color_check(self, color): norm_color = tuple([c / 255.0 for c in color]) color1 = np.float32([[norm_color]]) hsv = cv2.cvtColor(color1, cv2.COLOR_RGB2HSV) h, s, v = tuple(hsv[0, 0, :]) self._operator_interface.print_to_console('COLOR: = {},{},{}\n'.format( h, s, v)) return (self._station_config.DISP_CHECKER_L_HsvH <= h <= self._station_config.DISP_CHECKER_H_HsvH and self._station_config.DISP_CHECKER_L_HsvS <= s <= self._station_config.DISP_CHECKER_H_HsvS)
def red_detect(img): # HSV色空間に変換 hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV) # 赤色のHSVの値域1 hsv_min = np.array([0, 127, 0]) hsv_max = np.array([30, 255, 255]) mask1 = cv.inRange(hsv, hsv_min, hsv_max) # 赤色のHSVの値域2 hsv_min = np.array([150, 127, 0]) hsv_max = np.array([179, 255, 255]) mask2 = cv.inRange(hsv, hsv_min, hsv_max) return mask1 + mask2
def url_to_image(): url = "http://192.168.43.1:8081/shot.jpg" # download the image, convert it to a NumPy array, and then read # it into OpenCV format res = urllib.urlopen(url) image = np.asarray(bytearray(res.read()), dtype="uint8") image = cv2.imdecode(image, cv2.IMREAD_COLOR) # perform the actual resizing of the image according to scaling_factor height, width = image.shape[:2] resized = cv2.resize(image, (width/scaling_factor, height/scaling_factor), interpolation = cv2.INTER_AREA) # Return gray sale image gray = cv2.cvtColor(resized, cv2.COLOR_BGR2GRAY) return gray
def render_deepdreamvideo(): import cv print("CV is working") cap = cv.VideoCapture('SampleFile.mkv') while (cap.isOpened()): ret, frame = cap.read() gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) cv.imshow('frame', gray) if cv.waitKey(1) & 0xFF == ord('q'): break cap.release() cv.destroyAllWindows()
def red_detect(self, img): '''赤色のマスク''' # HSV色空間に変換 hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV) # 赤色のHSVの値域1 hsv_min = np.array([0, 127, 0]) hsv_max = np.array([30, 255, 255]) mask1 = cv.inRange(hsv, hsv_min, hsv_max) # 赤色のHSVの値域2 hsv_min = np.array([150, 127, 0]) hsv_max = np.array([179, 255, 255]) mask2 = cv.inRange(hsv, hsv_min, hsv_max) # mask画像を保存 #cv.imwrite('red_mask_'+ img, mask1 + mask2) return mask1 + mask2
video = cv.VideoCapture(0) background=0 for i in range(30): ret,background=video.read() background=np.flip(background, axis=1m) while True: ret,img=video.read() img=np.flip(img, axis=1) hsv=cv.cvtColor(img, cv.COLOR_BGR2HSV) blur=cv.GaussianBlur(hsv, (35,35), 0) cv.imshow("Display", img) lower=np.array([0,120,70]) upper=np.array([10,255,255]) mask01=cv.inRange(hsv, lower, upper) cv.imshow("Background", background) cv.imshow("mask01", mask01) k=cv.waitKey(1) if k==ord('q'): break video.release() cv.destroyAllWindows()
def run(self): # Capture first frame to get size frame = cv.QueryFrame(self.capture) frame_size = cv.GetSize(frame) grey_image = cv.CreateImage(cv.GetSize(frame), cv.IPL_DEPTH_8U, 1) moving_average = cv.CreateImage(cv.GetSize(frame), cv.IPL_DEPTH_32F, 3) difference = None while True: # Capture frame from webcam color_image = cv.QueryFrame(self.capture) # Smooth to get rid of false positives cv.Smooth(color_image, color_image, cv.CV_GAUSSIAN, 3, 0) if not difference: # Initialize difference = cv.CloneImage(color_image) temp = cv.CloneImage(color_image) cv.ConvertScale(color_image, moving_average, 1.0, 0.0) else: cv.RunningAvg(color_image, moving_average, 0.020, None) # Convert the scale of the moving average. cv.ConvertScale(moving_average, temp, 1.0, 0.0) # Minus the current frame from the moving average. cv.AbsDiff(color_image, temp, difference) # Convert the image to grayscale. cv.hsv cv.cvtColor(color_image, cv.hsv, CV_BGR2HSV) inRange(hsv, Scalar(0, 58, 89), Scalar(25, 173, 229), cv.bw) # Dilate and erode to get object blobs # cv.Dilate(grey_image, grey_image, None, 18) # cv.Erode(grey_image, grey_image, None, 10) # Calculate movements storage = cv.CreateMemStorage(0) contour = cv.FindContours(grey_image, storage, cv.CV_RETR_CCOMP, cv.CV_CHAIN_APPROX_SIMPLE) points = [] while contour: # Draw rectangles bound_rect = cv.BoundingRect(list(contour)) contour = contour.h_next() pt1 = (bound_rect[0], bound_rect[1]) pt2 = (bound_rect[0] + bound_rect[2], bound_rect[1] + bound_rect[3]) points.append(pt1) points.append(pt2) cv.Rectangle(color_image, pt1, pt2, cv.CV_RGB(255, 0, 0), 1) num_points = len(points) if num_points: # Draw bullseye in midpoint of all movements x = y = 0 for point in points: x += point[0] y += point[1] x /= num_points y /= num_points center_point = (x, y) cv.Circle(color_image, center_point, 40, cv.CV_RGB(255, 255, 255), 1) cv.Circle(color_image, center_point, 30, cv.CV_RGB(255, 100, 0), 1) cv.Circle(color_image, center_point, 20, cv.CV_RGB(255, 255, 255), 1) cv.Circle(color_image, center_point, 10, cv.CV_RGB(255, 100, 0), 5) # Display frame to user cv.ShowImage("Target", color_image) # Listen for ESC or ENTER key c = cv.WaitKey(7) % 0x100 if c == 27 or c == 10: break
def run(self): # Capture first frame to get size frame = cv.QueryFrame(self.capture) frame_size = cv.GetSize(frame) grey_image = cv.CreateImage(cv.GetSize(frame), cv.IPL_DEPTH_8U, 1) moving_average = cv.CreateImage(cv.GetSize(frame), cv.IPL_DEPTH_32F, 3) difference = None while True: # Capture frame from webcam color_image = cv.QueryFrame(self.capture) # Smooth to get rid of false positives cv.Smooth(color_image, color_image, cv.CV_GAUSSIAN, 3, 0) if not difference: # Initialize difference = cv.CloneImage(color_image) temp = cv.CloneImage(color_image) cv.ConvertScale(color_image, moving_average, 1.0, 0.0) else: cv.RunningAvg(color_image, moving_average, 0.020, None) # Convert the scale of the moving average. cv.ConvertScale(moving_average, temp, 1.0, 0.0) # Minus the current frame from the moving average. cv.AbsDiff(color_image, temp, difference) # Convert the image to grayscale. cv.hsv cv.cvtColor(color_image, cv.hsv, CV_BGR2HSV); inRange(hsv, Scalar(0, 58, 89), Scalar(25, 173, 229), cv.bw); # Dilate and erode to get object blobs # cv.Dilate(grey_image, grey_image, None, 18) # cv.Erode(grey_image, grey_image, None, 10) # Calculate movements storage = cv.CreateMemStorage(0) contour = cv.FindContours(grey_image, storage, cv.CV_RETR_CCOMP, cv.CV_CHAIN_APPROX_SIMPLE) points = [] while contour: # Draw rectangles bound_rect = cv.BoundingRect(list(contour)) contour = contour.h_next() pt1 = (bound_rect[0], bound_rect[1]) pt2 = (bound_rect[0] + bound_rect[2], bound_rect[1] + bound_rect[3]) points.append(pt1) points.append(pt2) cv.Rectangle(color_image, pt1, pt2, cv.CV_RGB(255,0,0), 1) num_points = len(points) if num_points: # Draw bullseye in midpoint of all movements x = y = 0 for point in points: x += point[0] y += point[1] x /= num_points y /= num_points center_point = (x, y) cv.Circle(color_image, center_point, 40, cv.CV_RGB(255, 255, 255), 1) cv.Circle(color_image, center_point, 30, cv.CV_RGB(255, 100, 0), 1) cv.Circle(color_image, center_point, 20, cv.CV_RGB(255, 255, 255), 1) cv.Circle(color_image, center_point, 10, cv.CV_RGB(255, 100, 0), 5) # Display frame to user cv.ShowImage("Target", color_image) # Listen for ESC or ENTER key c = cv.WaitKey(7) % 0x100 if c == 27 or c == 10: break
import cv as cv2 # Loading the cascades face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml') # Defining a function that will do the detections def detect(gray, frame): faces = face_cascade.detectMultiScale(gray, 1.3, 5) for (x, y, w, h) in faces: cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2) roi_gray = gray[y:y + h, x:x + w] roi_color = frame[y:y + h, x:x + w] eyes = eye_cascade.detectMultiScale(roi_gray, 1.1, 3) for (ex, ey, ew, eh) in eyes: cv2.rectangle(roi_color, (ex, ey), (ex + ew, ey + eh), (0, 255, 0), 2) return frame # Doing some Face Recognition with the webcam video_capture = cv2.VideoCapture(0) while True: _, frame = video_capture.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) canvas = detect(gray, frame) cv2.imshow('Video', canvas) if cv2.waitKey(1) & 0xFF == ord('q'): break video_capture.release() cv2.destroyAllWindows()
import cv #To read the image img = cv2.imread("path") #To convert the image to grey imgGray = cv.cvtColor(img,cv2.COLOR_BGR2GRAY) cv2.imshow("Gray Image",imgGray) #To convert into blur//Blur value (must be odd numbers) imgBlur = cv2.GaussianBlur(img,(7,7),0) cv2.imshow("Gray Image",imgBlur) #To Convert to canny //threshold value imgCanny = cv.Canny(img,100,100) cv2.imshow("Canny Image",imgCanny) #To enhance the canny image by dilation method #Dilation makes the image tick and one can tell the difference in color #Eroded makes the imgae thin import numpy as np kernel = np.ones(5,5),np.uint8) imgDialation = cv2.dilate(imgCanny,kernel,iteration = 1); cv2.imshow("Dilated Image",imgDialation); #Erosion imgEroded = cv2.erode(imgDialation,kernel,iteration = 1);
def HSV(image): image_HSV= cv.cvtColor(image, cv.COLOR_BGR2HSV) H, S, V = cv.split(image_HSV) return image_HSV
# Resize the image for faster processing img = Image.open(cam_cap) reduced_percent = 0.1 out = img.resize([int(reduced_percent * s) for s in img.size]) imagePath = "/sdcard/image.jpg" out.save(imagePath) sleep(3) # Set the haarcascade file path cascPath = "/sdcard/haarcascade_frontalface_default.xml" # Create the haar cascade faceCascade = cv2.CascadeClassifier(cascPath) # Read the image image = cv2.imread(imagePath) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Detect faces in the image faces = faceCascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5, minSize=(30, 30), flags=cv2.cv.CV_HAAR_SCALE_IMAGE) print("Found {0} faces!".format(len(faces))) # Draw a rectangle around the faces for (x, y, w, h) in faces: cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2) #save the image cv2.imwrite('/sdcard/out.jpg', image)
import cv as cv2 import numpy as np img = cv2.imread('opencv_logo.png',0) img = cv2.medianBlur(img,5) cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR) circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,20, param1=50,param2=30,minRadius=0,maxRadius=0) circles = np.uint16(np.around(circles)) for i in circles[0,:]: # draw the outer circle cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2) # draw the center of the circle cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3) cv2.imshow('detected circles',cimg) cv2.waitKey(0) cv2.destroyAllWindows()
import cv as cv2 import numpy as np img = cv2.imread('opencv_logo.png', 0) img = cv2.medianBlur(img, 5) cimg = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) circles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=30, minRadius=0, maxRadius=0) circles = np.uint16(np.around(circles)) for i in circles[0, :]: # draw the outer circle cv2.circle(cimg, (i[0], i[1]), i[2], (0, 255, 0), 2) # draw the center of the circle cv2.circle(cimg, (i[0], i[1]), 2, (0, 0, 255), 3) cv2.imshow('detected circles', cimg) cv2.waitKey(0) cv2.destroyAllWindows()
print('--(!)Error loading face cascade') exit(0) feature_params = dict( maxCorners = 100, qualityLevel = 0.3, minDistance = 7, blockSize = 7 ) # Parameters for lucas kanade optical flow lk_params = dict( winSize = (15,15), maxLevel = 2, criteria = (cv.TERM_CRITERIA_EPS | cv.TERM_CRITERIA_COUNT, 10, 0.03)) # First frame ret, prev_frame = cap.read() prev_frame_gray = cv.cvtColor(prev_frame, cv.COLOR_BGR2GRAY) # detect face frame face_frame = detect_face(prev_frame, face_cascade) # Region Selection roi_features_gray = cv.cvtColor(feature_extraction(face_frame), cv.COLOR_BGR2GRAY) # Find Corners p0 = cv.goodFeaturesToTrack(roi_features_gray, mask = None, **feature_params) vertical_component = np.array([[]]) while(cap.isOpened()): ret, current_frame = cap.read() if ret == False: break current_frame_gray = cv.cvtColor(current_frame, cv.COLOR_BGR2GRAY) # apply lucas Kanade optical flow for trajectories