def take_snapshot(self): # get image from webcam if not self.camera_is_on(): self.use_camera() self.flushCameraBuffer() # this reduces the frame delay frame = cv.QueryFrame(self.capture) self.create_folder_if_not_exist() image_name = "capture_%s.jpg" % time.strftime("%y_%m_%d_%H_%M_%S") image_path = os.path.join(PICTURE_PATH, image_name) cv.SaveImage(image_path, frame) cv.SaveImage(os.path.join(PICTURE_PATH, "current.jpg"), frame) # this is the preview image return image_name
def grab_images(video_file, frame_inc=100, delay=100): """ Walks through the entire video and save image for each increment """ my_video = init_video(video_file) if my_video != None: # Display the video and save evry increment frames cpt = 0 img = cv2.QueryFrame(my_video) if img != None: cv2.NamedWindow("Vid", cv2.CV_WINDOW_AUTOSIZE) else: return None nFrames = int( cv2.GetCaptureProperty(my_video, cv2.CV_CAP_PROP_FRAME_COUNT)) while cpt < nFrames: for ii in range(frame_inc): img = cv2.QueryFrame(my_video) cpt += 1 cv2.ShowImage("Vid", img) out_name = "" + str(cpt) + ".jpg" cv2.SaveImage(out_name, img) print out_name, str(nFrames) cv2.WaitKey(delay) else: return None
def save_captures(num, captures): dir = "data/capture_%02d" % num if not os.path.exists(dir): os.mkdir(dir) for i, img in enumerate(captures): path = os.path.join(dir, "card_%04d.png" % i) if os.path.exists(path): raise Exception("path %s already exists!" % path) cv2.SaveImage(path, img)
def saveAsJPG(img): global fname_temp lt = time.localtime(time.time()) if ((lt[5] % 2) == 0): fname = "%04d%02d%02d%02d%02d%02d" % (lt[0], lt[1], lt[2], lt[3], lt[4], lt[5]) if (fname != fname_temp): print("frame saved at " + fname) cv2.SaveImage("img/" + fname + ".jpg", img) fname_temp = fname
def display_rgb(dev, data, timestamp): global keep_running cv.Image = frame_convert.video_cv(data) img = cv.CreateImage(cv.GetSize(cv.Image), cv.IPL_DEPTH_16S, 3) cv.ShowImage('RGB', cv.Image) for x in range(1, 5): name = "img%d" % (x) cv.SaveImage('name.png', cv.Image) time.sleep(1) if cv.WaitKey(10) == 27: keep_running = False
def save_image(img, _pos, _time, _pitch, number): _filename = "{}.jpeg".format("%02d" % number) cv2.SaveImage(_filename, img) im = Image.open(_filename) exif_dict = piexif.load(_filename) exif_dict["0th"][ piexif.ImageIFD.ImageDescription] = "pitch: {} postion: {}".format( _pitch, _pos) exif_bytes = piexif.dump(exif_dict) im.save(_filename, "jpeg", exif=exif_bytes) return
def take_preview_image(self): # get image from webcam if not self.camera_is_on(): self.use_camera() self.flushCameraBuffer() # this reduces the frame delay frame = cv.QueryFrame(self.capture) if frame is None: self.close_camera() return self.create_folder_if_not_exist() cv.SaveImage(os.path.join(PICTURE_PATH, "current.jpg"), frame) # this is the preview image
def detect_features(self, faces, image_filename): """ Detects Features in an list of faces and returns the images """ logging.debug('start detect %s features for file %s (train.py)' %(parameter.description_method, image_filename)) keypoints = [] descriptors = [] # detect features and save for i in range(len(faces)): if not parameter.face_enlargement == None: faces[i] = tools.enlarge_image(faces[i], parameter.face_enlargement) logging.debug('Cropped face from file %s has been enlarged with factor %.3f (surf-detector.py)' % (image_filename, parameter.face_enlargement)) face_numpy = np.asarray(faces[i]) # convert image for further processing # compute surf calculation if parameter.description_method == 'surf': surf = cv2.SURF(parameter.hessian_threshold, parameter.nOctaves, parameter.nOctaveLayers) # threshold, number of octaves, number of octave layers within each octave (http://opencv.itseez.com/modules/features2d/doc/feature_detection_and_description.html, http://www.mathworks.de/help/toolbox/vision/ref/detectsurffeatures.html) tmpkeypoints, tmpdescriptors = surf.detect(face_numpy, None, False) # extracting the SURF keys if len(tmpdescriptors) == 0: logging.warn('No descriptors found for a face in file %s (surf-detector.py)' % (image_filename)) else: tmpdescriptors.shape = (-1, surf.descriptorSize()) # change the shape of the descriptor from 1-dim to 2-dim (notwendig, damit die Funktionen - match_bruteforce - bei der Suche funktionieren) logging.info('%d Features found in file %s: face number %d (surf-detector.py)' % (len(tmpdescriptors), image_filename, (i+1))) # compute sift calculation if parameter.description_method == 'sift': cv.SaveImage('tmp-sift.jpg', faces[i]) sift.process_image('tmp-sift.jpg',"tmp.sift") l1,tmpdescriptors = sift.read_features_from_file("tmp.sift") tmpkeypoints = [] if tmpdescriptors == None: logging.warn('No descriptors found for a face in file %s (surf-detector.py)' % (image_filename)) else: for j in range(len(l1)): keypoint = cv2.KeyPoint(l1[j][0], l1[j][1], l1[j][2], l1[j][3]) tmpkeypoints.append(keypoint) logging.info('%d Features found in file %s: face number %d (surf-detector.py)' % (len(tmpdescriptors), image_filename, (i+1))) keypoints.append(tmpkeypoints) # add keypoints do list even when none are found descriptors.append(tmpdescriptors) # add descriptors do list even when none are found return(keypoints, descriptors)
def process_image(self, slider_pos): global cimg, source_image1, ellipse_size, maxf, maxs, eoc, lastcx,lastcy,lastr """ This function finds contours, draws them and their approximation by ellipses. """ stor = cv.CreateMemStorage() # Create the destination images cimg = cv.CloneImage(self.source_image) cv.Zero(cimg) image02 = cv.CloneImage(self.source_image) cv.Zero(image02) image04 = cv.CreateImage(cv.GetSize(self.source_image), cv.IPL_DEPTH_8U, 3) cv.Zero(image04) # Threshold the source image. This needful for cv.FindContours(). cv.Threshold(self.source_image, image02, slider_pos, 255, cv.CV_THRESH_BINARY) # Find all contours. cont = cv.FindContours(image02, stor, cv.CV_RETR_LIST, cv.CV_CHAIN_APPROX_NONE, (0, 0)) maxf = 0 maxs = 0 size1 = 0 for c in contour_iterator(cont): if len(c) > ellipse_size: PointArray2D32f = cv.CreateMat(1, len(c), cv.CV_32FC2) for (i, (x, y)) in enumerate(c): PointArray2D32f[0, i] = (x, y) # Draw the current contour in gray gray = cv.CV_RGB(100, 100, 100) cv.DrawContours(image04, c, gray, gray,0,1,8,(0,0)) if iter == 0: strng = segF + '/' + 'contour1.png' cv.SaveImage(strng,image04) color = (255,255,255) (center, size, angle) = cv.FitEllipse2(PointArray2D32f) # Convert ellipse data from float to integer representation. center = (cv.Round(center[0]), cv.Round(center[1])) size = (cv.Round(size[0] * 0.5), cv.Round(size[1] * 0.5)) if iter == 1: if size[0] > size[1]: size2 = size[0] else: size2 = size[1] if size2 > size1: size1 = size2 size3 = size # Fits ellipse to current contour. if eoc == 0 and iter == 2: rand_val = abs((lastr - ((size[0]+size[1])/2))) if rand_val > 20 and float(max(size[0],size[1]))/float(min(size[0],size[1])) < 1.5: lastcx = center[0] lastcy = center[1] lastr = (size[0]+size[1])/2 if rand_val > 20 and float(max(size[0],size[1]))/float(min(size[0],size[1])) < 1.4: cv.Ellipse(cimg, center, size, angle, 0, 360, color,2, cv.CV_AA, 0) cv.Ellipse(source_image1, center, size, angle, 0, 360, color,2, cv.CV_AA, 0) elif eoc == 1 and iter == 2: (int,cntr,rad) = cv.MinEnclosingCircle(PointArray2D32f) cntr = (cv.Round(cntr[0]), cv.Round(cntr[1])) rad = (cv.Round(rad)) if maxf == 0 and maxs == 0: cv.Circle(cimg, cntr, rad, color, 1, cv.CV_AA, shift=0) cv.Circle(source_image1, cntr, rad, color, 2, cv.CV_AA, shift=0) maxf = rad elif (maxf > 0 and maxs == 0) and abs(rad - maxf) > 30: cv.Circle(cimg, cntr, rad, color, 2, cv.CV_AA, shift=0) cv.Circle(source_image1, cntr, rad, color, 2, cv.CV_AA, shift=0) maxs = len(c) if iter == 1: temp3 = 2*abs(size3[1] - size3[0]) if (temp3 > 40): eoc = 1
im_data = Image.fromarray(im, 'RGB') filt_min, filt_max = net.blobs['upsample'].data.min( ), net.blobs['upsample'].data.max() imgo = net.blobs['upsample'].data.copy().transpose(0, 2, 3, 1)[0] fig = plt.figure() a = fig.add_subplot(1, 2, 1) #lum_img = img[:,:,0] #imgplot = plt.imshow(lum_img) imgplot = plt.imshow(im_data.astype(np.uint8), interpolation='none', cmap='gray') a.set_title('Before') #plt.colorbar(ticks=[0.1,0.3,0.5,0.7], orientation ='horizontal') a = fig.add_subplot(1, 2, 2) imgplot = plt.imshow(imgo.astype(np.uint8), interpolation='none', cmap='gray') a.set_title('After') plt.show() b = cv2.cvtColor(imgo.astype(np.uint8), cv2.COLOR_GRAY2BGR) cv2.SaveImage('transformedCat.png', b) #plt.title("original image") #plt.imshow(im) #plt.axis('off') #plt.imshow(imgo, interpolation='none') #plt.show()
def GetBoth(): # freenect.stop_depth() # freenect.stop_video() depth = freenect.sync_get_depth()[0] video = freenect.sync_get_video()[0] # freenect.start_depth() # freenect.start_video() return (DoUsefulConvert8(depth), DoNiceConvertRGB(video)) def StopKinect(): freenect.sync_stop() if __name__ == "__main__": while True: image = GetDepth8() if image: cv.ShowImage("Kinect view", image) cv.SaveImage("/home/borg/freenect.png", image) else: print "invalid image %s" % repr(image) k = cv.WaitKey(5) if k == 0x1b: print 'ESC pressed. Exiting ...' break
def showNaoImage(IP, PORT,camID):#参数分别为IP、PORT、摄像头ID(区分上下摄像头) #链接nao的摄像头 camProxy = ALProxy("ALVideoDevice", IP, PORT) resolution = 2 # VGA`` colorSpace = 11 # RGB videoClient = camProxy.subscribe("python_client", resolution, colorSpace, 5)#设置分辨率、帧速、颜色空间 t0 = time.time() camProxy.setParam(18,camID)#设置摄像头 naoImage = camProxy.getImageRemote(videoClient)#将获取的图像赋给naoImage t1 = time.time() camProxy.unsubscribe(videoClient) imageWidth = naoImage[0] imageHeight = naoImage[1] array = naoImage[6] #naoImage[6]为imagedata im_cv = numpy.zeros((imageHeight, imageWidth, 3), numpy.uint8)#初始化图像im_cv im_cv.data = array #将从摄像头获取的图像copy到im_cv,转为mat #转化颜色空间由BGR到RGB b, g, r = cv2.split(im_cv) img1 = cv2.merge([r, g, b]) #转mat到cvmat img3 = cv2.cv.fromarray(img1) cv2.SaveImage("test22.bmp",img3) #转换颜色空间到HSV imgHSV = cv2.CreateImage(cv2.GetSize(img3), 8, 3) cv2.CvtColor(img3, imgHSV, cv2.CV_RGB2HSV) cimg,cimg_c=hsvProceed(imgHSV,camID) #调用hsvProceed处理图像,返回二值图 #圈取最小矩形框 #初始化 storage = cv2.cv.CreateMemStorage(0) cnts = cv2.FindContours(cimg,storage,cv2.cv.CV_RETR_LIST,cv2.cv.CV_CHAIN_APPROX_SIMPLE) currtnt=cnts Area = 0 left_right = 0 up_down = 0 #为不同摄像头设置不同筛选条件 if camID == 0: areamax = 2500 areamin = 40 valuemin = 25 value_w = 641 valuemax = 481 else : areamax = 5000 areamin = 400 valuemin = 0 value_w = 500 valuemax = 400 while cnts: rect = cv2.cv.BoundingRect(cnts,0)#获得单连通矩形框 area = rect[2]*rect[3] #获得矩形框面积 #获得矩形框中心点坐标 rect_center_x = rect[0] + rect[2] / 2 rect_center_y = rect[1] + rect[3] / 2 #调用choose0文件下的radio函数,筛选圆形部分 radio_c = choose0.radio(cimg_c,rect) radio = float(rect[2])/rect[3] #计算矩形框的长宽比 #以下if语句均为筛选条件 if rect[1]>=valuemin: if rect[1]<=valuemax: if rect[0]<=value_w: if area > areamin: if area < areamax: if radio > 0.6: if radio < 1.6: if radio_c == 1: cv2.cv.DrawContours(img3, cnts, (255, 255, 0), (255, 255, 0), 0, 1)#画出单连通轮廓 cv2.cv.Rectangle(img3,(rect[0],rect[1]),(rect[0]+rect[2],rect[1]+rect[3]),(0,0,255),1)#画出矩形框 rect_center_x = rect[0] + rect[2]/2 rect_center_y = rect[1] + rect[3]/2 #计算通过条件的矩形框的面积以及在图像中的位置 Area = rect[2]*rect[3] left_right = rect_center_x - cimg.width / 2 up_down = rect_center_y - cimg.height / 2 cnts = cnts.h_next() return Area,left_right,up_down #返回球的面积以及在图像中的位置
cv.createTrackbar('Depth Window', 'Video', depth_window, 1, toggle_depth_window) cv.createTrackbar('Threshold Window', 'Video', threshold_window, 1, toggle_threshold_window) cv.createTrackbar('Detector Window', 'Video', detector_window, 1, toggle_detector_window) # main program loop while 1: if depth_window: show_depth() if threshold_window: show_threshold(); if detector_window: show_detector(); show_video() key = cv.WaitKey(5) & 0xFF if key == 27: break; elif key == 115: print '"s" key pressed, saving RGB image to file RGB.jpg' cv2.imwrite('RGB.jpg', freenect.sync_get_video()[0]); elif key == 100 and depth_window: print '"d" key pressed, saving depth image to file DEPTH.jpg' cv.SaveImage('DEPTH.jpg', depth_image)
import cv2 as cv img = cv.LoadImage("friend1.jpg") image_size = cv.GetSize(img) #获取图片的大小 greyscale = cv.CreateImage(image_size, 8, 1) #建立一个相同大小的灰度图像 cv.CvtColor(img, greyscale, cv.CV_BGR2GRAY) #将获取的彩色图像,转换成灰度图像 storage = cv.CreateMemStorage(0) #创建一个内存空间,人脸检测是要利用,具体作用不清楚 cv.EqualizeHist(greyscale, greyscale) #将灰度图像直方图均衡化,貌似可以使灰度图像信息量减少,加快检测速度 # detect objects cascade = cv.Load('haarcascade_frontalface_alt2.xml') #加载Intel公司的训练库 #检测图片中的人脸,并返回一个包含了人脸信息的对象faces faces = cv.HaarDetectObjects(greyscale, cascade, storage, 1.2, 2, cv.CV_HAAR_DO_CANNY_PRUNING, (50, 50)) #获得人脸所在位置的数据 j = 0 #记录个数 for (x, y, w, h), n in faces: j += 1 cv.SetImageROI(img, (x, y, w, h)) #获取头像的区域 cv.SaveImage("face" + str(j) + ".jpg", img) #保存下来
def saveImage(self, filename): # Save the image using the given filename cv.SaveImage(filename, self.image)
post_on_facebook(people[final_label], counter, picture_name) final_5= [] ''' cv2.imshow("Video Window", frame) counter+= 1 #if (cv2.waitKey(5) & 0xFF== 27): #break command = cv2.waitKey(5) if command == ord('q'): print("Ending program") break #elif brk == 1: # print("Detected !!") # break elif command == ord('s'): print("Saving image") cv2.SaveImage("img00.jpg",frame) #elif counter == 100: # print("Ending program by program") # break cv2.destroyAllWindows() time.sleep(2) # GPIO.output(21,GPIO.HIGH)
def landmarkdetect(IP, PORT, camID): camProxy = ALProxy("ALVideoDevice", IP, PORT) resolution = 2 # VGA`` colorSpace = 11 # RGB videoClient = camProxy.subscribe("python_client", resolution, colorSpace, 5) camProxy.setParam(18, camID) naoImage = camProxy.getImageRemote(videoClient) camProxy.unsubscribe(videoClient) imageWidth = naoImage[0] imageHeight = naoImage[1] array = naoImage[6] im_cv = numpy.zeros((imageHeight, imageWidth, 3), numpy.uint8) im_cv.data = array #im_cv = cv2.imread("img3.jpg",1) b, g, r = cv2.split(im_cv) img1 = cv2.merge([r, g, b]) img3 = cv2.fromarray(img1) #img3=cv.LoadImage("img3.jpg",1) cv.SaveImage("save1.jpg", img3) imgHSV = cv.CreateImage(cv.GetSize(img3), 8, 3) cv.CvtColor(img3, imgHSV, cv.CV_RGB2HSV) cimg, cimg_c = hsvProceed(imgHSV) # cv.ShowImage("imgHSV", imgHSV) # cv.ShowImage("cimg", cimg) # cv.WaitKey(5) # # img3 = cv.LoadImage("save1.jpg",1) # imgHSV = cv.CreateImage(cv.GetSize(img3), 8, 3) # # cv.CvtColor(img3, imgHSV, cv.CV_RGB2HSV) # cimg, cimg_c=hsvProceed(imgHSV) # cv.ShowImage("s",cimg_c) storage = cv2.CreateMemStorage(0) cnts = cv.FindContours(cimg, storage, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) currtnt = cnts x = 0.0 Area = 0 left_right = 0 up_down = 0 if camID == 0: areamax = 6000 areamin = 350 value = img3.height / 7 else: areamax = 5000 areamin = 400 value = 0 while cnts: rect = cv2.BoundingRect(cnts, 0) area = rect[2] * rect[3] rect_center_x = rect[0] + rect[2] / 2 rect_center_y = rect[1] + rect[3] / 2 # if camID == 1: # radio_c = choose0.radio(cimg_c,rect) # if camID == 0: # radio_c = choose0.choose02(cimg_c,rect) radio = float(rect[2]) / rect[3] if rect[1] > 10: if area > areamin: if area < areamax: if radio > 0.1: if radio < 1.0: #if radio_c == 1: # cv2.cv.DrawContours(img3, cnts, (255, 255, 0), (255, 255, 0), 0, 1) # cv2.cv.Rectangle(img3,(rect[0],rect[1]),(rect[0]+rect[2],rect[1]+rect[3]),(0,0,255),1) #choose0.radio(cimg_c,rect) rect_center_x = rect[0] + rect[2] / 2 rect_center_y = rect[1] + rect[3] / 2 Area = rect[2] * rect[3] left_right = rect_center_x - cimg.width / 2 up_down = rect_center_y - cimg.height / 2 x, y = getloacation(rect[2], left_right) cnts = cnts.h_next() # cv2.cv.ShowImage("fsfs", img3) # cv.WaitKey(1) return Area, left_right, x
if __name__ == "__main__": orig = cv.LoadImage( r"C:\git\Python-Snippets\Image Recognition\images\D2C-Logins - RunDate 2019-10-03 - Part (22).image" ) #Convert in black and white res = cv.CreateImage(cv.GetSize(orig), 8, 1) cv.CvtColor(orig, res, cv.CV_BGR2GRAY) #Operations on the image openCloseImage(res) dilateImage(res, 2) erodeImage(res, 2) smoothImage(res, 5) thresholdImage(res, 150, cv.CV_THRESH_BINARY_INV) #Get contours approximated contourLow = getContours(res, 3) #Draw them on an empty image final = cv.CreateImage(cv.GetSize(res), 8, 1) cv.Zero(final) cv.DrawContours(final, contourLow, cv.Scalar(255), cv.Scalar(255), 2, cv.CV_FILLED) cv.ShowImage("orig", orig) cv.ShowImage("image", res) cv.SaveImage("modified.png", res) cv.ShowImage("contour", final) cv.SaveImage("contour.png", final) cv.WaitKey(0)
import time if __name__ == '__main__': cv.namedWindow("camera", 1) #开启ip摄像头 video = "http://*****:*****@172.16.200.214:8081/" capture = cv.VideoCapture(video) num = 0 while True: img = cv.QueryFrame(capture) cv.ShowImage("camera", img) #按键处理,注意,焦点应当在摄像头窗口,不是在终端命令行窗口 key = cv.WaitKey(10) if key == 27: #esc键退出 print('esc break...') break if key == ord(' '): #保存一张图像 num = num + 1 filename = "frames_%s.jpg" % num cv.SaveImage(filename, img) del (capture) cv.DestroyWindow("camera")
# @Description: createImage.py # @Author: 孤烟逐云zjy # @Date: 2020/5/3 9:49 # @SoftWare: PyCharm # @CSDN: https://blog.csdn.net/zjy123078_zjy # @博客园: https://www.cnblogs.com/guyan-2020/ import cv2 as cv im = cv.LoadImage('./images/photo01.jpg') # get the img thum = cv.CreateImage((im.width / 2, im.height / 2), 8, 3) cv.Resize(im, thum) cv.SaveImage('thum.jpg', thum)
import cv2 import sys storage = cv2.CreateMemStorage() image_path = "yusei.jpg" img = cv2.imread(image_path) hc = cv2.Load("../data/haarcascades/haarcascade_frontalface_default.xml") faces = cv2.HaarDetectObjects(img, hc, storage, 1.1, 3, 0, (0, 0)) max = 0 maxh = 0 maxw = 0 resx = 0 resy = 0 for (x, y, w, h), n in faces: if max < w * h: maxw = w maxh = h resx = x resy = y max = w * h sub = cv2.GetSubRect(img, (resx, resy, maxw, maxh)) cv2.SaveImage("face_" + sys.argv[1], sub)
#!/usr/bin/python import cv2 #import the openCV lib to python import serial #import the pyserial module #Module -1: Image Processing hc = cv2.imread( '/home/george/PycharmProjects/Embeded image processing system/haarcascade_frontalface_alt2.xml' ) img = cv2.imshow('/home/jayneil/beautiful-faces.jpg', 0) faces = cv2.HaarDetectObjects(img, hc, cv2.CreateMemStorage()) a = 1 print(faces) for (x, y, w, h), n in faces: cv2.Rectangle(img, (x, y), (x + w, y + h), 255) cv2.SaveImage("faces_detected.jpg", img) dst = cv2.imread('faces_detected.jpg') cv2.NamedWindow('Face Detected', cv2.CV_WINDOW_AUTOSIZE) cv2.imshow('Face Detected', dst) cv2.WaitKey(5000) cv2.DestroyWindow('Face Detected') #Module -2: Trigger Pyserial if faces == []: ser = serial.Serial('/dev/ttyUSB0', 9600) print(ser) ser.write('N') else: ser = serial.Serial('/dev/ttyUSB0', 9600)
import cv2 imageBuffer = cv2.LoadImage( 'images/digits_sudoku2.png' ) nW = 468 nH = 99 smallerImage = cv2.CreateImage( (nH, nW), imageBuffer.depth, imageBuffer.nChannels ) cv2.Resize( imageBuffer, smallerImage , interpolation=cv2.CV_INTER_CUBIC ) cv2.SaveImage( 'images/digits_sudoku3.png', smallerImage )