视频分解图片,图片合成视频

转载自: http://blog.csdn.net/ioswyl88219/article/details/18152419

视频视频分解视频合成AVAssetImageGenerato

工作当中用到了相关的技术,现在特别记录一下

分解视频

[objc] view plaincopyprint?

  1. <span style="font-size:18px;">
  2. //分解视频
  3. - (void)resolveMovWithUrl:(NSURL *)movUrl{
  4. //得到url的资源,转为asset
  5. AVAsset *myAsset = [[AVURLAsset alloc] initWithURL:movUrl options:nil];
  6. NSParameterAssert(myAsset);
  7. //初始化AVAssetImageGenerator
  8. self.imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:myAsset] ;
  9. self.imageGenerator.appliesPreferredTrackTransform = YES;//加这句话,取出的是正确方向的图片
  10. self.imageGenerator.requestedTimeToleranceBefore = kCMTimeZero;
  11. self.imageGenerator.requestedTimeToleranceAfter = kCMTimeZero;
  12. //得到秒数
  13. Float64 _durationSeconds = CMTimeGetSeconds([myAsset duration]);
  14. __block float Second = 0.0;
  15. __block int num = 0;
  16. NSString *path = [self backPath];
  17. NSLog(@"%@",path);
  18. dispatch_semaphore_t sem = dispatch_semaphore_create(0);
  19. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
  20. dispatch_async(dispatch_get_main_queue(), ^{
  21. [MBProgressHUD showHUDAddedTo:self.view animated:YES];
  22. });
  23. while ((_durationSeconds - Second)>0) {
  24. NSLog(@"%f",_durationSeconds - Second);
  25. CMTime rTime = CMTimeMakeWithSeconds(Second, NSEC_PER_SEC);
  26. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  27. @autoreleasepool
  28. {
  29. //根据帧数取出图片
  30. CGImageRef image= [self.imageGenerator copyCGImageAtTime:rTime actualTime:NULL error:NULL];
  31. if (image)
  32. {
  33. UIImage *img = [[UIImage alloc] initWithCGImage:image];
  34. NSData *imageData = UIImagePNGRepresentation(img);
  35. NSString *pathNum = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.png",num]];
  36. [imageData writeToFile:pathNum atomically:NO];
  37. CGImageRelease(image);
  38. NSString *actualTimeString =CFBridgingRelease(CMTimeCopyDescription(NULL, rTime));
  39. NSLog(@"photo:%d",num);
  40. NSLog(@"%@",actualTimeString);
  41. //调用dispatch_semaphore_signal函数,使计数器+1
  42. dispatch_semaphore_signal(sem);
  43. }else{
  44. dispatch_async(dispatch_get_main_queue(), ^{
  45. [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
  46. });
  47. }
  48. }
  49. });
  50. Second +=0.083;
  51. //一直等待,直到信号量计数器大于等于1
  52. dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
  53. num+=1;
  54. }
  55. dispatch_async(dispatch_get_main_queue(), ^{
  56. num = 0;
  57. Second = 0.0;
  58. [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
  59. });
  60. });
  61. }</span>

图片合成视频

[objc] view plaincopyprint?

    1. <span style="font-size:18px;">
    2. - (void)initRecord
    3. {
    4. //是否是第一次添加图片
    5. self.firstImgAdded = FALSE;
    6. //video路径
    7. NSString* fileName = [NSString stringWithFormat:@"%d.mov", (int)[[NSDate date] timeIntervalSince1970]];
    8. self.videoPath = [NSString stringWithFormat:@"%@/%@", [self getLibarayPath], fileName];
    9. //设置一个gcd队列
    10. writeQueue = dispatch_queue_create("recording_queue", DISPATCH_QUEUE_PRIORITY_DEFAULT);
    11. CGSize frameSize = imageRect.size;
    12. NSError* error = nil;
    13. //创建写入对象
    14. self.videoWriter = [[AVAssetWriter alloc] initWithURL:[NSURL fileURLWithPath:self.videoPath] fileType:AVFileTypeQuickTimeMovie error:&error];
    15. //如果出错,打印错误内容
    16. if(error)
    17. {
    18. NSLog(@"error creating AssetWriter: %@",[error description]);
    19. self.videoWriter = nil;
    20. return;
    21. }
    22. //设置参数
    23. NSDictionary *videoSettings = [NSDictionary dictionaryWithObjectsAndKeys:
    24. AVVideoCodecH264, AVVideoCodecKey,
    25. [NSNumber numberWithInt:frameSize.width], AVVideoWidthKey,
    26. [NSNumber numberWithInt:frameSize.height], AVVideoHeightKey,
    27. nil nil];
    28. //输入对象
    29. self.writerInput = [AVAssetWriterInput
    30. assetWriterInputWithMediaType:AVMediaTypeVideo
    31. outputSettings:videoSettings];
    32. //属性设置
    33. NSMutableDictionary *attributes = [[NSMutableDictionary alloc] init];
    34. [attributes setObject:[NSNumber numberWithUnsignedInt:kCVPixelFormatType_32ARGB] forKey:(NSString*)kCVPixelBufferPixelFormatTypeKey];
    35. [attributes setObject:[NSNumber numberWithUnsignedInt:frameSize.width] forKey:(NSString*)kCVPixelBufferWidthKey];
    36. [attributes setObject:[NSNumber numberWithUnsignedInt:frameSize.height] forKey:(NSString*)kCVPixelBufferHeightKey];
    37. //通过属性和writerInput 创建一个新的Adaptor
    38. self.adaptor = [AVAssetWriterInputPixelBufferAdaptor
    39. assetWriterInputPixelBufferAdaptorWithAssetWriterInput:self.writerInput
    40. sourcePixelBufferAttributes:attributes];
    41. //添加输入,必须在开始写入之前
    42. [self.videoWriter addInput:self.writerInput];
    43. self.writerInput.expectsMediaDataInRealTime = YES;
    44. //开始写入
    45. [self.videoWriter startWriting];
    46. [self.videoWriter startSessionAtSourceTime:kCMTimeZero];
    47. }
    48. #pragma mark - 视频合成
    49. static int count = 0;
    50. - (void)startCamera
    51. {
    52. NSMutableArray *arr = [self allFilesAtPath:[self backPath]];
    53. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    54. dispatch_async(dispatch_get_main_queue(), ^{
    55. [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    56. });
    57. while (arr.count -count) {
    58. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%d.png",[self backPath],count]];
    59. CGImageRef image1 = image.CGImage;
    60. [self writeImage:image1 withIndex:count];
    61. NSLog(@"%d",count);
    62. count ++;
    63. }
    64. [self.writerInput markAsFinished];
    65. [self.videoWriter finishWriting];
    66. //        [self combineWithAudio:num];
    67. dispatch_async(dispatch_get_main_queue(), ^{
    68. count = 0;
    69. [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    70. });
    71. });
    72. }
    73. - (void)writeImage:(CGImageRef)img withIndex:(NSInteger)curCount
    74. {
    75. CVPixelBufferRef buffer = NULL;
    76. if (self.videoWriter == nil)
    77. {
    78. NSLog(@"error~~~~~~~~~~~");
    79. }
    80. if (self.firstImgAdded == FALSE)
    81. {
    82. buffer = [self pixelBufferFromCGImage:img];
    83. BOOL result = [self.adaptor appendPixelBuffer:buffer withPresentationTime:kCMTimeZero];
    84. if (result == NO) //failes on 3GS, but works on iphone 4
    85. {
    86. NSLog(@"failed to append buffer");
    87. }
    88. if(buffer)
    89. {
    90. CVBufferRelease(buffer);
    91. }
    92. self.firstImgAdded = TRUE;
    93. }
    94. else
    95. {
    96. if (self.adaptor.assetWriterInput.readyForMoreMediaData)
    97. {
    98. CMTime frameTime = CMTimeMake(1, FramePerSec);
    99. CMTime lastTime = CMTimeMake(curCount, FramePerSec);
    100. CMTime presentTime = CMTimeAdd(lastTime, frameTime);
    101. buffer = [self pixelBufferFromCGImage:img];
    102. BOOL result = [self.adaptor appendPixelBuffer:buffer withPresentationTime:presentTime];
    103. if (result == NO) //failes on 3GS, but works on iphone 4
    104. {
    105. NSLog(@"failed to append buffer");
    106. NSLog(@"The error is %@", [self.videoWriter error]);
    107. }
    108. else
    109. {
    110. NSLog(@"write ok");
    111. }
    112. if(buffer)
    113. {
    114. CVBufferRelease(buffer);
    115. }
    116. }
    117. else
    118. {
    119. NSLog(@"error");
    120. }
    121. }
    122. }
    123. - (CVPixelBufferRef)pixelBufferFromCGImage:(CGImageRef)image
    124. {
    125. NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
    126. [NSNumber numberWithBool:TRUE], kCVPixelBufferCGImageCompatibilityKey,
    127. [NSNumber numberWithBool:TRUE],kCVPixelBufferCGBitmapContextCompatibilityKey,
    128. nil nil];//是否兼容
    129. CVPixelBufferRef pxbuffer = NULL;
    130. CVReturn status = CVPixelBufferCreate(kCFAllocatorDefault, imageRect.size.width,
    131. imageRect.size.height, kCVPixelFormatType_32ARGB, (__bridge CFDictionaryRef) options,
    132. &pxbuffer);//返回kCVReturnSuccess kCFAllocatorDefault = nil
    133. status=status;
    134. NSParameterAssert(status == kCVReturnSuccess && pxbuffer != NULL);//判断类型
    135. CVPixelBufferLockBaseAddress(pxbuffer, 0);//访问地址
    136. voidvoid *pxdata = CVPixelBufferGetBaseAddress(pxbuffer);
    137. NSParameterAssert(pxdata != NULL);
    138. CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
    139. CGContextRef context = CGBitmapContextCreate(pxdata, imageRect.size.width,
    140. imageRect.size.height, 8, 4*imageRect.size.width, rgbColorSpace,
    141. kCGImageAlphaNoneSkipFirst);
    142. NSParameterAssert(context);
    143. CGContextConcatCTM(context, CGAffineTransformMakeRotation(0));
    144. CGContextDrawImage(context, CGRectMake(0, 0, imageRect.size.width, imageRect.size.height), image);
    145. CGColorSpaceRelease(rgbColorSpace);
    146. CGContextRelease(context);
    147. CVPixelBufferUnlockBaseAddress(pxbuffer, 0);
    148. return pxbuffer;
    149. }</span>
时间: 2024-07-30 14:33:51

视频分解图片,图片合成视频的相关文章

IOS 视频分解图片、图片合成视频

在IOS视频处理中,视频分解图片和图片合成视频是IOS视频处理中经常遇到的问题,这篇博客就这两个部分对IOS视频图像的相互转换做一下分析. (1)视频分解图片 这里视频分解图片使用的是AVAssetImageGenerator,利用这个class可以很方便的实现不同时间戳下,视频帧的抓取.注意一般这种视频分解图片帧的方法都是放在子线程中的,而UI更新操作都是放在主线程中的.下面来看看核心代码: _imageGenerator = [[AVAssetImageGenerator alloc] in

【人脸识别0】视频分解图片与图片合成视频

一,引言 目标:这小节主要通过两个demo熟悉视频分解图片与图片合成视频的OpenCV的应用 环境:python3.6+OpenCV3.3.1 二,示例 Demo1:视频分解图片 目标: 1.指定文件夹中读取视频文件 2.将视频文件分解为图片 3.将图片保存在指定文件夹中 # -*-coding:utf-8-*- #author: lyp time: 2018/8/8 # 视频分解图片 import cv2 cap = cv2.VideoCapture('E:/Envs/opencvdemo/o

在Ubuntu14.04下安装 ffmpeg-2.4.13(处理视频用,将视频保存为图片序列)

首先在 http://www.ffmpeg.org/olddownload.html 下载 ffmpeg-2.4.13.tar.bz2 : 然后安装 yasm 和 libx264: apt-get install yasm aptitude install libx264-dev 安装依赖: aptitude install libfaac-dev aptitude install libmp3lame-dev aptitude install libtheora-dev aptitude in

ios学习笔记图片+图片解释(c语言 oc语言 ios控件 ios小项目 ios小功能 swift都有而且笔记完整喔)

下面是目录其中ios文件夹包括了大部分ios控件的介绍和演示,swift的时完整版,可以学习完swift(这个看的是swift刚出来一周的视频截图,可能有点赶,但是完整),c语言和oc语言的也可以完整的学习完所需知识,,其他文件夹的内容如其名说描述一样 没张图片都有文字说明,可以需要该功能的时候搜索一下然后打开图片就可以学习到 网盘下载地址:需要的话给留言我再传上去 http://www.cnblogs.com/langtianya原创 ios学习笔记图片+图片解释(c语言 oc语言 ios控件

IOS如何创建视频缩略图片

//将完整的图片和缩略后的图片写入临时文件夹中     NSData *pngImage = UIImagePNGRepresentation(thumbnail);     if ([pngImage writeToFile:[NSString stringWithFormat:@"%@/tempImage.png",TEMP_FOLDER] atomically:YES]) { UIImage *myThumbNail = [[UIImage alloc] initWithData

在opencv下读取视频保存为图片

VideoCapture capture; capture.open("D:\\car.avi");//读取视频 对于视频下一帧的读取: capture>>frameImg;//读取视频流下一帧控制,字符重载 对于视频的图片保存 std::stringstream ss;//存储图片路径保存信息 ss<<"D:/output/image_"<<setfill('0')<<setw(3)<<(nCount-1

从视频中提取图片,对图片做人脸检测并截取人脸区域

环境配置:VS2013+opencv2.4.10+libface.lib 参考博客:http://blog.csdn.net/augusdi/article/details/11042329 http://www.1024do.com/?p=1296 首先给出视频处理的函数video_process.hpp #include <stdio.h> #include <opencv2/opencv.hpp> #include "facedetect-dll.h" #

分享一段代码,基于 ffmpeg 的视频转化为图片

代码如下: function Video2Bmp(const strVideoFileName, strSavePath: string): Boolean; var pfc1 : PAVFormatContext; pfc2 : PAVFormatContext; intVideoStreamIndex: Integer; pps : PPAVStream; III : Integer; pcc : PAVCodecContext; pCodec : PAVCodec; pFrameVdo :

jQuery实现类似视频播放功能的图片播放器插件

jquery Image Player是一款可以像视频播放一样逐张播放图片的图片播放器jQuery插件.当你需要介绍你的某个产品和项目的时候,这个插件就可以发挥它的强大作用.你可以将产品或项目的各个功能做成图片,然后使用该插件来逐帧播放. 现在大多数的产品和项目介绍使用的都是gif图片或flash,甚至是直接嵌入视频,使用这个图片播放器插件,你可以自由的控制哪张图片需要播放,还可以设置淡入淡出效果,图片滑动效果,图片标题等等. 效果演示:http://www.htmleaf.com/Demo/2