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 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 get_cam(): INTERNAL_CAM = 0 cv.NamedWindow("test", cv.CV_WINDOW_AUTOSIZE) capture = cv.CaptureFromCAM(INTERNAL_CAM) if not capture: print "No camera captured. Exiting..." sys.exit(1) run = True while run: frame = cv.QueryFrame(capture) cv.ShowImage("test", frame) run = cv.waitKey(10) != 113
def imageLoop(): global lastSymbol frame = cv.QueryFrame(capture) width_percent = 100.0 / 100 height_percent = 90.0 / 100 origin_x = int(frame.width * (1 - width_percent)/2) origin_y = int(frame.height * (1 - height_percent)/2) width = int(frame.width * width_percent) height = int(frame.height * height_percent) # print origin_x, origin_y, width, height subsection = cv.GetSubRect(frame, (origin_x+1, origin_y+1, width-1, height-1)) # subsection = frame cv.Rectangle(frame, (origin_x, origin_y), (origin_x + width, origin_y + height), (255,0,0)) cm_im = cv.CreateImage((subsection.width, subsection.height), cv.IPL_DEPTH_8U, 1) cv.ConvertImage(subsection, cm_im) image = zbar.Image(cm_im.width, cm_im.height, 'Y800', cm_im.tostring()) scanner.scan(image) # extract results for symbol in image: # do something useful with results if symbol.type == zbar.Symbol.ISBN10 and lastSymbol != symbol.data: lastSymbol = symbol.data searchBook(symbol.data) # print 'decoded', symbol.type, 'symbol', '"%s"' % symbol.data # cv.ShowImage("w1", frame) # cv.ShowImage("w2", subsection) refreshWindow("w1", frame) key = cv.waitKey(100) if key != -1: if key == 113: sys.exit(0) logText("Key: ", key)
if __name__ == '__main__': map_image = cv.LoadImageM(map_file, 1) cv.NamedWindow("map", 1) scale = 1.0 if (map_image.cols > 800): scale = map_image.cols / 800.0 dst = cv.CreateMat(int(map_image.rows / scale), int(map_image.cols / scale), cv.CV_8UC3) cv.Resize(map_image, dst) map_image = dst cv.ShowImage("map", map_image) def mouse_cb(event, x, y, flags, param): if (event == cv.CV_EVENT_LBUTTONUP): print x * scale, y * scale pt = (x, y) cv.Circle(map_image, pt, int(38 / scale), cv.Scalar(255, 0, 0), -1) cv.ShowImage("map", map_image) pass cv.SetMouseCallback('map', mouse_cb) while cv.waitKey(25) != 27: time.sleep(0.025) pass cv.DestroyWindow('map')
cv.imshow('window,img) def track_y(y): cv.line(img, (x, 0), (x, h), RED, d) cv.line(img, (0, y), (w, y), RED, d) cv.imshow('window,img) file = 'messi.jpg' # img = cv.imread(file, cv.IMREAD_GRAYSCALE) img0 = cv.imread(file, cv.IMREAD_COLOR) cv.imshow('window,img) w, h = 800, 600 x, y = 100, 100 d = 1 cv.createTrackbar('x', 'window, x, w, track_x) cv.createTrackbar('y', 'window, y, h, track_y) cv.line(img, (x, 0), (x, h), RED, d) cv.line(img, (0, y), (w, y), RED, d) cv.imshow('window,img) k = cv.waitKey(0) print('key', k) cv.imwrite('messigray.png',img) cv.destroyAllWindows()
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()
#show_img('image',bg_img) #=========================================== # GUI # top = Tkinter.Tk() top.title('Control Window') center_window(top, 300, 240) top.maxsize(600, 400) top.minsize(300, 240) top.protocol("WM_DELETE_WINDOW", quit) b1 = Tkinter.Button(top, text ="stop processing ", command = btn1_callback) b1.pack() b2 = Tkinter.Button(top, text ="start processing", command = btn2_callback) b2.pack() b3 = Tkinter.Button(top, text ="======exit======", command = btn3_callback) b3.pack() top.mainloop() #=========================================== cv.waitKey(0) # close window when a key press is detected cv2.destroyAllWindows() cv.WaitKey(1) cv.WaitKey(1) cv.WaitKey(1) cv.WaitKey(1)
__author__ = 'ober' from numpy import * import cv # load and show an image in gray scale image = cv.LoadImage('flish2.bmp',cv.CV_LOAD_IMAGE_GRAYSCALE) imageBlur = cv.CreateImage(cv.GetSize(image), image.depth, image.nChannels) # print some image properties print 'Depth:',image.depth,'# Channels:',image.nChannels print 'Size:',image.width,image.height print 'Pixel values average',cv.Avg(image) # create the window cv.NamedWindow('my window', cv.CV_WINDOW_AUTOSIZE) dstSobel = cv.CreateMat(image.height, image.width, cv.CV_32FC1) cv.Smooth(image, imageBlur, cv.CV_BLUR, 15, 15) cv.Sobel(imageBlur,dstSobel,1,1,5) cv.ShowImage('my sobal', dstSobel) #cv.Canny(imageBlur,dstSobel,50,100,3) cv.ShowImage('my window', imageBlur) #cv.ShowImage('sobel', dstSobel) cv.WaitKey() cv.SaveImage('imageSobel.jpg', dstSobel) cv.waitKey(0);
class StitchJob(object): bag_name = "default.bag" stitch_file_name = "default.jpg" camera_info = CameraInfo() def __init__(self, bag_name, stitch_file_name): self.bag_name = bag_name self.stitch_file_name = stitch_file_name self.bridge = CvBridge() def stitch(self): bag = rosbag.Bag(self.bag_name) saved_camera_info = False img_n = 0 pano_dir = tempfile.mkdtemp("pano") image_names = [] camera = pano.Camera() blur_detector = pano.BlurDetector() for topic, msg, t in bag.read_messages(topics=['camera_info']): if ('camera_info' in topic): print "reading camera info" K = pcv.Mat(3, 3, pcv.CV_32FC1) K.fromarray(msg.K) img_size = pcv.Size(msg.width, msg.height) camera.setCameraIntrinsics(K, pcv.Mat(), img_size) break options = pano.Options() options.camera = camera options.stitch_size = pcv.Size(4000, 2000) options.directory = pano_dir #options.image_names.assign(image_names) params = options.fitter_params params.error_thresh = 6 params.inliers_thresh = 15 params.maxiters = 100 params.nNeeded = 2 options.stitch_output = self.stitch_file_name stitcher = pano.StitchEngine(options) for topic, msg, t in bag.read_messages(topics=['image']): if ('image' in topic): try: cv_image = self.bridge.imgmsg_to_cv(msg, "rgb8") b_prob = blur_detector.checkBlur(cv_image) print "image blur prob = %f" % b_prob pano_image = pcv.convertCvMat2Mat(cv_image) stitcher.addNewImage(pano_image) img_n += 1 except CvBridgeError, e: print e bag.close() blended = cv.CreateMat(2000, 4000, cv.CV_8UC3) stitcher.stitch(blended, self.stitch_cb) cv.NamedWindow("blended", pcv.CV_WINDOW_KEEPRATIO) cv.ShowImage("blended", blended) cv.SaveImage(self.stitch_file_name, blended) cv.waitKey(0) return True
import cv, cv2 img = cv.imread("cones_plus_shadowed_barrel.jpg", cv2.CV_LOAD_IMAGE_COLOR) cv.namedWindow('Normal Image') cv.imshow('Normal Image', img) hsv_img = img cv.CvtColor(img,hsv_img,cv.CV_RGB2HSV) cv.namedWindow('HSV Image') cv.imshow('HSV Image', hsv_img) cv.waitKey(0) cv.destroyAllWindows()
time_ = time.gmtime() time_out = '%02i.%02i.%02i.%03i' %(time_[3], time_[4], time_[5], abs(ros_time.to_sec()-round(ros_time.to_sec()))*1000) print 'Frame: ', frame pc = np.array([pts_pos.T, pts_color]) # Nx6 pointcloud im_pos = np.reshape(pts_pos.T, (480, 640, -1)) ### Find object(s) finder = ObjectFinder(pc) # cProfile.run('pc, im = finder.run(min_=.6, max_=.9)', '/home/colin/profile_object') pdb.set_trace() pc, im = finder.run(min_=.5, max_=1.0) if viz: cv.ShowImage("Detector", im/np.max(np.max(im))) key = cv.waitKey(33) ### Texture detection # cProfile.run('classScores = classifier.run(im)', '/home/colin/profile_classifier') classScores, locs = classifier.run(im) dID_ind = np.argmax(classScores) dID_score= classScores[dID_ind] dID = objectNames[dID_ind] print "Objects in order" dID_ind_nonzero = np.nonzero(classScores>0)[0] dID_scores_nz = classScores[dID_ind_nonzero] dID_names_nz = objectNames[dID_ind_nonzero]
time_[3], time_[4], time_[5], abs(ros_time.to_sec() - round(ros_time.to_sec())) * 1000) print 'Frame: ', frame pc = np.array([pts_pos.T, pts_color]) # Nx6 pointcloud im_pos = np.reshape(pts_pos.T, (480, 640, -1)) ### Find object(s) finder = ObjectFinder(pc) # cProfile.run('pc, im = finder.run(min_=.6, max_=.9)', '/home/colin/profile_object') pdb.set_trace() pc, im = finder.run(min_=.5, max_=1.0) if viz: cv.ShowImage("Detector", im / np.max(np.max(im))) key = cv.waitKey(33) ### Texture detection # cProfile.run('classScores = classifier.run(im)', '/home/colin/profile_classifier') classScores, locs = classifier.run(im) dID_ind = np.argmax(classScores) dID_score = classScores[dID_ind] dID = objectNames[dID_ind] print "Objects in order" dID_ind_nonzero = np.nonzero(classScores > 0)[0] dID_scores_nz = classScores[dID_ind_nonzero] dID_names_nz = objectNames[dID_ind_nonzero] dID_ind_nzSort = np.argsort(dID_scores_nz)
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()
# capture frames from the camera for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True): # grab the raw NumPy array representing the image, then initialize the timestamp # and occupied/unoccupied text image = frame.array gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale( gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags=cv.CASCADE_SCALE_IMAGE ) # Draw a rectangle around the faces for (x, y, w, h) in faces: cv.rectangle( image, (x, y), (x+w, y+h), (0, 255, 0), 2) # show the frame cv.imshow("Frame", image) key = cv.waitKey(1) & 0xFF # clear the stream in preparation for the next frame rawCapture.truncate(0) # if the `q` key was pressed, break from the loop if key == ord("q"): break
import cv as cv import numpy as np img = np.zeros((512, 512, 3), np.uint8) # 填充像素 img.fill(64) text = "OpenCV for Python" cv.putText(img, text, (10,40),cv.FONT_HERSHEY_SIMPLEX,\ 1,(0,255,255),1,cv.LINE_AA) cv.putText(img, text, (10,80),cv.FONT_HERSHEY_PLAIN,\ 1,(0,255,255),2,cv.LINE_AA) cv.putText(img, text, (10,120),cv.FONT_HERSHEY_DUPLEX,\ 1,(0,255,255),1,cv.LINE_AA) cv.putText(img, text, (10,160),cv.FONT_HERSHEY_COMPLEX,\ 1,(0,255,255),2,cv.LINE_AA) cv.putText(img, text, (10,200),cv.FONT_HERSHEY_TRIPLEX,\ 1,(0,255,255),1,cv.LINE_AA) cv.putText(img, text, (10,240),cv.FONT_HERSHEY_COMPLEX_SMALL,\ 1,(0,255,255),2,cv.LINE_AA) cv.putText(img, text, (10,280),cv.FONT_HERSHEY_SCRIPT_SIMPLEX,\ 1,(0,255,255),1,cv.LINE_AA) cv.putText(img, text, (10,320),cv.FONT_HERSHEY_SCRIPT_COMPLEX,\ 1,(0,255,255),2,cv.LINE_AA) cv.imshow('imgae', img) cv.waitKey() cv.destroyAllWindows()
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()
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()