python opencv图片编码为h264文件的实例
python部分
#!/usr/bin/envPython #coding=utf-8 fromctypesimport* fromPyQt5.QtCoreimport* fromPyQt5.QtGuiimport* fromPyQt5.QtWidgetsimport* importtime importnumpyasnp importcv2 importstruct importdatetime fromnumbaimportjit importos cam_dict={} classCamInfo: def__init__(self,cam_no=0,deviceid="default",cam_name="default"): self.cam_no=cam_no self.deviceid=deviceid self.cam_name=cam_name @jit deftrans(data,size,height,width): bbb=string_at(data,size) nparr=np.fromstring(bbb,np.uint8) r=nparr.reshape(height,width,3) returnr defstr2char_p(str_v): pStr=c_char_p() pStr.value=str_v returnpStr defcallb_stream(data,size,cam_no,height,width): r=trans(data,size,height,width) r=cv2.cvtColor(r,cv2.COLOR_RGB2BGR) counter=datetime.datetime.now().strftime('%Y%m%d_%H%M%S_%f') #print(1,counter) cv2.imshow(str(cam_no),r) cv2.waitKey(1) defcallb_camerainfo(cam_no,camera_info,camera_info_size): #print(cast(camera_info,c_char_p).value) #print(str(cast(camera_info,c_char_p).value)) bbb=string_at(camera_info,camera_info_size) info=str(bbb,encoding="utf-8").split(",") cam_dict[cam_no]=CamInfo(cam_no,info[1],info[2]) print("camerainfo",cam_dict[cam_no].cam_no,cam_dict[cam_no].cam_name,cam_dict[cam_no].deviceid) classMythread(QThread): #定义信号,定义参数为str类型 breakSignal=pyqtSignal(str,list) def__init__(self,parent=None): super().__init__(parent) #super(Mythread,self).__init__() defcallb_error(self,err_type,cam_no,msg_no,msg_level,msg_txt,msg_txtlen): print("myerror",err_type,cam_no,msg_no,msg_level,msg_txt,msg_txtlen) defrun(self): dll=CDLL(r"./hik_client.dll") width=60 height=40 dll.pre_encode.restype=c_void_p ret=dll.pre_encode(width,height) ret=cast(ret,c_void_p) foriinrange(20000): n=i%200+1 img=cv2.imread("bmp/"+str(n)+".bmp") len=img.shape[0]*img.shape[1]*img.shape[2] #img=np.transpose(img,(1,0,2)) #b,g,r=cv2.split(img) #b=b.reshape(-1) #g=g.reshape(-1) #r=r.reshape(-1) #b=np.append(b,g) #img=np.append(b,r) img=img.reshape(-1) #b,g,r=cv2.split(img) #b=b.reshape(-1) #g=g.reshape(-1) #r=r.reshape(-1) #b=np.append(b,g) #img=np.append(b,r) INPUT=c_int*len #实例化一个长度为2的整型数组 input=INPUT() #为数组赋值(input这个数组是不支持迭代的) foriinrange(len): input[i]=img[i] #bytes(aaaa,encoding="utf-8") a=dll.push_rtsp(input,len,ret) QCoreApplication.instance().quit() #print("encode_ok",i) #b=string_at(a,1280*720*3) #print(b) #nparr=np.fromstring(b,np.uint8) ##print(nparr[-10:-1],min(nparr),max(nparr)) #img_decode=cv2.imdecode(nparr,cv2.IMREAD_COLOR) ##ifimg_decode: #cv2.imshow("sadf",img_decode) ##cv2.imwrite(str(index)+".jpg",img_decode) #cv2.waitKey(0) # # # # #ErrorCall=CFUNCTYPE(c_void_p,c_int,c_int,c_int,c_int,c_char_p,c_int) #error_callback=ErrorCall(self.callb_error) #dll.set_callback(error_callback) #CamCall=CFUNCTYPE(c_void_p,c_int,c_char_p,c_int) #caminfo_CamCall=CamCall(callb_camerainfo) ##print(b) #ifnotos.path.exists("video"): #os.makedirs("video") #ip=b"127.0.0.1" #port=8888 #print("startconn") #ret=-1 #while(ret): #print("connserver...") #ret=dll.tcp_init(str2char_p(ip),port) #time.sleep(0.3) #if(ret==0): #type=1 #ret=dll.getcameralist(type,caminfo_CamCall) #if(1): ##deviceId=b"af94a68df0124d1fbf0fc2b07f3b3c3a" #cam_no=14 #else: #print("tcperror") #foriinrange(2000000): ##发出信号 #a=[i,i+1] #self.breakSignal.emit(str(i),a) ##让程序休眠 #time.sleep(0.5) if__name__=='__main__': app=QApplication([]) dlg=QDialog() dlg.resize(400,300) dlg.setWindowTitle("自定义按钮测试") dlgLayout=QVBoxLayout() dlgLayout.setContentsMargins(40,40,40,40) btn=QPushButton('测试按钮') dlgLayout.addWidget(btn) dlgLayout.addStretch(40) dlg.setLayout(dlgLayout) dlg.show() defchuli(a,s): #dlg.setWindowTitle(s) btn.setText(a+str(s[0]*10)) #创建线程 thread=Mythread() ##注册信号处理函数 thread.breakSignal.connect(chuli) ##启动线程 thread.start() dlg.exec_() app.exit()
c++动态库部分
#include"stdafx.h" #include"CVdll.h" #include"SimpleLog.h" #include#include #include #include"opencv2/opencv.hpp" #include"Ws2tcpip.h" #include #include #include #include #include #pragmacomment(lib,"ws2_32.lib") #include usingnamespacecv; extern"C" { #include"libavcodec/avcodec.h" #include"libavformat/avformat.h" #include"libswscale/swscale.h" #include"libavdevice/avdevice.h" #include"libavutil/log.h" //#include"libavutil/imgutils.h" }; //说明,动态库需要拷贝三个文件,否则重连会出问题 char*testchar(intplus1){ char*str="helloworld111111"; returnstr; } char*testimg(char*data,intlength){ char*str="helloworld111111"; returnstr; } intoutbuf_size=100000; classRtmp_tool{ public: intnWidth=0; intnHeight=0; AVCodecContext*c; AVFrame*m_pRGBFrame=newAVFrame[1];//RGB帧数据 AVFrame*m_pYUVFrame=newAVFrame[1];;//YUV帧数据 uint8_t*yuv_buff;// uint8_t*outbuf; SwsContext*scxt; FILE*f=NULL; }; void*pre_encode(intwidth,intheight){ Rtmp_tool*rtmp_tool; rtmp_tool=newRtmp_tool(); intnLen; intfileI; rtmp_tool->nWidth=width; rtmp_tool->nHeight=height; av_register_all(); avcodec_register_all(); //AVFrame*m_pRGBFrame=newAVFrame[1];//RGB帧数据 //AVFrame*m_pYUVFrame=newAVFrame[1];;//YUV帧数据 AVCodecContext*c=NULL; AVCodecContext*in_c=NULL; AVCodec*pCodecH264;//编码器 //查找h264编码器 pCodecH264=avcodec_find_encoder(AV_CODEC_ID_H264); c=avcodec_alloc_context3(pCodecH264); c->bit_rate=3000000;//putsampleparameters c->width=width;// c->height=height;// //framespersecond AVRationalrate; rate.num=1; rate.den=5; c->time_base=rate;//(AVRational){1,25}; c->gop_size=10;//emitoneintraframeeverytenframes c->max_b_frames=1; c->thread_count=1; c->pix_fmt=AV_PIX_FMT_YUV420P;//PIX_FMT_RGB24; //av_opt_set(c->priv_data,/*"preset"*/"libvpx-1080p.ffpreset",/*"slow"*/NULL,0); //打开编码器 if(avcodec_open2(c,pCodecH264,NULL)<0) printf("不能打开编码库"); intsize=c->width*c->height; rtmp_tool->yuv_buff=(uint8_t*)malloc((size*3)/2);//sizeforYUV420 //图象编码 rtmp_tool->outbuf=(uint8_t*)malloc(outbuf_size); intu_size=0; constchar*filename="0_Data.h264"; rtmp_tool->f=fopen(filename,"wb"); if(!rtmp_tool->f) { printf("couldnotopen%s\n",filename); exit(1); } //初始化SwsContext rtmp_tool->scxt=sws_getContext(c->width,c->height,AV_PIX_FMT_BGR24,c->width,c->height,AV_PIX_FMT_YUV420P,SWS_POINT,NULL,NULL,NULL); rtmp_tool->c=c; returnrtmp_tool; } char*push_rtsp(int*plus1,intlen,void*vp){ Rtmp_tool*rtmp_tool=(Rtmp_tool*)vp; for(inti=0;i c;//(AVCodecContext*)vp; printf("2%d%d\n",c->width,c->height); //--------------- AVPacketavpkt; AVFrame*m_pRGBFrame=rtmp_tool->m_pRGBFrame; AVFrame*m_pYUVFrame=rtmp_tool->m_pYUVFrame; /*unsignedchar*pBmpBuf; pBmpBuf=newunsignedchar[len];*/ //memcpy(rgb_buff,(uint8_t*)plus1,nDataLen); // avpicture_fill((AVPicture*)m_pRGBFrame,(uint8_t*)plus1,AV_PIX_FMT_RGB24,rtmp_tool->nWidth,rtmp_tool->nHeight); m_pRGBFrame->linesize[0]=c->width*3; m_pRGBFrame->linesize[1]=0; m_pRGBFrame->linesize[2]=0; m_pRGBFrame->linesize[3]=0; m_pRGBFrame->format=AV_PIX_FMT_RGB24; m_pRGBFrame->width=rtmp_tool->nWidth; m_pRGBFrame->height=rtmp_tool->nHeight; uint8_t*p=m_pRGBFrame->data[0]; inty=0,x=0; for(y=0;y nHeight;y++){ for(x=0;x nWidth;x++){ *p++=(uint8_t)plus1[(y*rtmp_tool->nWidth+x)*3];//R *p++=(uint8_t)plus1[(y*rtmp_tool->nWidth+x)*3+1];//G *p++=(uint8_t)plus1[(y*rtmp_tool->nWidth+x)*3+2];//B } } printf("1%d%d\n",rtmp_tool->nWidth,rtmp_tool->nHeight); //将YUVbuffer填充YUVFrame avpicture_fill((AVPicture*)m_pYUVFrame,(uint8_t*)rtmp_tool->yuv_buff,AV_PIX_FMT_YUV420P,rtmp_tool->nWidth,rtmp_tool->nHeight); //翻转RGB图像 //m_pRGBFrame->data[0]+=m_pRGBFrame->linesize[0]*(rtmp_tool->nHeight-1); //m_pRGBFrame->linesize[0]*=-1; //m_pRGBFrame->data[1]+=m_pRGBFrame->linesize[1]*(rtmp_tool->nHeight/2-1); //m_pRGBFrame->linesize[1]*=-1; //m_pRGBFrame->data[2]+=m_pRGBFrame->linesize[2]*(rtmp_tool->nHeight/2-1); //m_pRGBFrame->linesize[2]*=-1; //将RGB转化为YUV sws_scale(rtmp_tool->scxt,m_pRGBFrame->data,m_pRGBFrame->linesize,0,c->height,m_pYUVFrame->data,m_pYUVFrame->linesize); intgot_packet_ptr=0; av_init_packet(&avpkt); avpkt.data=rtmp_tool->outbuf; avpkt.size=outbuf_size; intu_size=avcodec_encode_video2(c,&avpkt,m_pYUVFrame,&got_packet_ptr); m_pYUVFrame->pts++; if(u_size==0){ intres=fwrite(avpkt.data,1,avpkt.size,rtmp_tool->f); if(res==0){ printf("000"); } else{ printf("1253"); } } //-------end--------- //Matmat; ////加载图片 //mat=imread("bgs.jpg",CV_LOAD_IMAGE_COLOR); //printf("a%d%d",mat.rows,mat.cols); ////if(!mat.empty()){ //intm,n; //n=mat.cols*3; //m=mat.rows; //unsignedchar*data=(unsignedchar*)malloc(sizeof(unsignedchar)*m*n); //intp=0; //for(inti=0;i (i,j); // p++; // } //} //*plus1=p; returnNULL; //return(char*)data; } structRecStruct//数据包 { intsize; intdata_type; intcam_no; interror_code; charrecvbuf[1500]; }; structSendStcuct { intsize; intdata_type; intcam_no; charsendbuf[1000]; }data_send; staticErrorCallBackg_errorcall=0; staticCamInfoCallBackg_caminfocall=0; typedefstructCameraInfo { std::ofstreamfoutV; inttimeInHour=-1; }caminfo; std::map cameraMap; //staticstd::map >namemap; staticSOCKETg_sockClient; HANDLEhMutex; //char*deviceId; /**判断str1是否以str2开头 *如果是返回1 *不是返回0 *出错返回-1 **/ intis_begin_with(constchar*str1,char*str2) { if(str1==NULL||str2==NULL) return-1; intlen1=strlen(str1); intlen2=strlen(str2); if((len1 1500){ if(g_errorcall!=0) g_errorcall(1,deviceInfo.cam_no,0,2,"data_recvtoolong",data_recv.size); printf("revedatatoolong%d\n",data_recv.size); continue; } if(data_recv.data_type==3) { if(g_errorcall){ charerr_str[10]; _itoa(data_recv.error_code,err_str,10);//正确解法一 g_errorcall(1,deviceInfo.cam_no,data_recv.error_code,4,err_str,0); } } elseif(data_recv.data_type==2) { null_count=0; display_count++; char*recemsg=data_recv.recvbuf; intis_null=is_begin_with(recemsg,"00000"); if(is_null==1){ printf("recv00000"); continue; } //printf("cam_no%d",data_recv.cam_no); //intcam_no=data_recv.cam_no; buf_size=data_recv.size; memcpy(buf,data_recv.recvbuf,buf_size); if(g_errorcall&&buf_size>1000&&display_count%20==0){ g_errorcall(2,deviceInfo.cam_no,1,0,"recedata",1);//err_type,cam_no,column,msg_level,msg_txt,spare display_count=0; } //保存流数据并分小时存储 time_ttt=time(NULL);//这句返回的只是一个时间cuo tm*t=localtime(&tt); autoiter=cameraMap.find(deviceInfo.cam_no); if(iter!=cameraMap.end()){ iter->second->foutV.write(data_recv.recvbuf,data_recv.size); if(t->tm_min==0&&(iter->second->timeInHour!=t->tm_hour)){ //判断间隔一小时 iter->second->timeInHour=t->tm_hour; iter->second->foutV.close(); time_ttt=time(NULL);//这句返回的只是一个时间cuo tm*t=localtime(&tt); charctmBegin[20]; strftime(ctmBegin,20,"/%Y%m%d%H%M",t); charstr3[80]; sprintf(str3,"createdata:%s%s%s",deviceInfo.cam_name,ctmBegin,".dat"); SLOG1(str3); printf("%s",deviceInfo.cam_name+std::string(ctmBegin)+".dat"); iter->second->foutV.open(deviceInfo.cam_name+std::string(ctmBegin)+".dat",ios::binary); } } returnbuf_size; } if(ret<0){ printf("WSAStartup()failed!\n"); continue; //return0; } } return0; } intsend_cmd(intcam_no,intsize,intdatatype,char*cam_name,SOCKET&sockClient){ SendStcuctdata_send; memset(&data_send,0,sizeof(structSendStcuct)); data_send.size=size; data_send.data_type=datatype; data_send.cam_no=cam_no; memcpy(data_send.sendbuf,cam_name,sizeof(char)*(size)); printf("data_sendlen%d\n",sizeof(data_send)); send(sockClient,(char*)&data_send,sizeof(structSendStcuct),0); return0; } inttcp_recv_conn(char*ip,intport,char*cam_name,intsize,intcam_no,FrameFunctcallback(char*a,intsize,intcam_no,intheight,intwidth)) { WSADATAwsaData; if(WSAStartup(MAKEWORD(2,2),&wsaData)!=0) { printf("初始化Winsock失败"); return-1; } SOCKADDR_INaddrSrv; addrSrv.sin_family=AF_INET; addrSrv.sin_port=htons(port); SOCKET sockClient=socket(AF_INET,SOCK_STREAM,0); intnRecvBuf=0;//设置为32K setsockopt(sockClient,SOL_SOCKET,SO_RCVBUF,(constchar*)&nRecvBuf,sizeof(int)); setsockopt(sockClient,SOL_SOCKET,SO_SNDBUF,(char*)&nRecvBuf,sizeof(int)); inet_pton(AF_INET,ip,&addrSrv.sin_addr.s_addr); if(connect(sockClient,(structsockaddr*)&addrSrv,sizeof(addrSrv))==-1) return-2; //throw"连接失败"; if(SOCKET_ERROR==sockClient){ printf("Socket()error:%d",WSAGetLastError()); return-3; } DeviceInfodeviceInfo; deviceInfo.cam_no=cam_no; deviceInfo.sockClient=sockClient; av_register_all(); unsignedversion=avcodec_version(); //printf("FFmpegversion:%d\n",version); //初始化流文件状态 time_ttt=time(NULL);//这句返回的只是一个时间cuo tm*t=localtime(&tt); charctmBegin[20]; strftime(ctmBegin,20,"/%Y%m%d%H%M",t); caminfocinfoInstance; deviceInfo.cam_name=cam_name; //std::stringdataName=cam_name; cinfoInstance.foutV.open(cam_name+std::string(ctmBegin)+".dat",ios::binary); //判断间隔一小时 cinfoInstance.timeInHour=t->tm_hour; cameraMap[cam_no]=&cinfoInstance; charstr3[20]; sprintf(str3,"camno:%dstart",cam_no); SLOG1(str3); AVFormatContext*pFormatCtx; inti,videoindex; AVCodecContext*pCodecCtx; AVCodec*pCodec; charfilepath[]="video.264"; //av_register_all(); avformat_network_init(); pFormatCtx=avformat_alloc_context(); //patha="C:\\Users\\sbd01\\Pictures\\ffmpegtest\\Debug\\video.dat"; //fp_open=fopen(patha.c_str(),"rb+"); unsignedchar*aviobuffer=(unsignedchar*)av_malloc(1512); send_cmd(cam_no,size,2,cam_name,sockClient); AVIOContext*avio=avio_alloc_context(aviobuffer,1512,0,&deviceInfo,read_buffer,NULL,NULL); pFormatCtx->pb=avio; //if(avformat_open_input(&pFormatCtx,patha.c_str(),NULL,NULL)!=0){ if(avformat_open_input(&pFormatCtx,NULL,NULL,NULL)!=0){ printf("Couldn'topeninputstream%d\n",cam_no); return-1; } printf("camno%dfindstream\n",cam_no); pFormatCtx->probesize=1000*1024; pFormatCtx->max_analyze_duration=10*AV_TIME_BASE; pCodec=NULL; while(pCodec==NULL){ printf("%dstartfindstreaminfo\n",cam_no); if(avformat_find_stream_info(pFormatCtx,NULL)<0){ printf("Couldn'tfindstreaminfo%d\n",cam_no); gotorestart_stream; continue; } videoindex=-1; for(i=0;i nb_streams;i++) if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO){ if(videoindex==-1){ videoindex=i; } //break; } if(videoindex==-1){ printf("%dDidn'tfindavideostream.\n",cam_no); gotorestart_stream; } pCodecCtx=pFormatCtx->streams[videoindex]->codec; //pCodec=avcodec_find_decoder(AV_CODEC_ID_H264); pCodec=avcodec_find_decoder(pCodecCtx->codec_id); if(pCodec==NULL){ printf("%dCodecnotfound\n",cam_no); gotorestart_stream; //return-1; } if(avcodec_open2(pCodecCtx,pCodec,NULL)<0){ printf("%dCouldnotopencodec.\n",cam_no); gotorestart_stream; continue; //return-1; } if(pCodecCtx->width<=0||pCodecCtx->height<=0||pCodecCtx->height>2000||pCodecCtx->width>3000){ printf("cam%dpCodecCtxerror1width%dheight%d",cam_no,pCodecCtx->width,pCodecCtx->height); gotorestart_stream; } gotook; restart_stream: printf("%drestart1",cam_no); avformat_free_context(pFormatCtx); printf("restart2"); //avformat_close_input(&pFormatCtx); pFormatCtx=NULL; pFormatCtx=avformat_alloc_context(); printf("restart3"); //av_freep(aviobuffer); //printf("restart4"); aviobuffer=(unsignedchar*)av_malloc(1512); printf("restart4"); AVIOContext*avio2=avio_alloc_context(aviobuffer,1512,0,&deviceInfo,read_buffer,NULL,NULL); pFormatCtx->pb=avio2; pFormatCtx->probesize=1000*1024; pFormatCtx->max_analyze_duration=10*AV_TIME_BASE; if(avformat_open_input(&pFormatCtx,NULL,NULL,NULL)!=0){ printf("2Couldn'topeninputstream%d\n",cam_no); //return-1; } printf("restart5\n"); pCodec=NULL; continue; ok: break; } printf("camno:%dcodename:%swidth%dheight%d\n",cam_no,pCodec->name,pCodecCtx->width,pCodecCtx->height); AVFrame*pFrame,*pFrameYUV; pFrame=av_frame_alloc(); pFrameYUV=av_frame_alloc(); intret,got_picture; if(g_errorcall){ char*cc; intlength=strlen(pCodec->name); cc=newchar[length+1]; strcpy(cc,pCodec->name); g_errorcall(0,cam_no,pCodecCtx->width,pCodecCtx->height,cc,11); } AVPacket*packet=(AVPacket*)av_malloc(sizeof(AVPacket)); structSwsContext*img_convert_ctx; img_convert_ctx=sws_getContext(pCodecCtx->width,pCodecCtx->height,pCodecCtx->pix_fmt,pCodecCtx->width,pCodecCtx->height,AV_PIX_FMT_RGB24,SWS_BICUBIC,NULL,NULL,NULL); uint8_t*out_buffer; printf("cam%dreadydecode2",cam_no); out_buffer=newuint8_t[avpicture_get_size(AV_PIX_FMT_RGB24,pCodecCtx->width,pCodecCtx->height)]; avpicture_fill((AVPicture*)pFrameYUV,out_buffer,AV_PIX_FMT_RGB24,pCodecCtx->width,pCodecCtx->height); //av_image_fill_arrays(pFrameYUV->data,pFrameYUV->linesize,out_buffer,AV_PIX_FMT_RGB24,pCodecCtx->width,pCodecCtx->height,1); printf("cam%dreadydecode3",cam_no); intdec_error_count=0; inttmp_test=0; while(av_read_frame(pFormatCtx,packet)>=0){ if(packet->stream_index==videoindex){ //tmp_test++; if(packet->size<50){ av_free_packet(packet); //printf("cam:%dpacketistoosmall%d\n",cam_no,packet->size); Sleep(3); continue; } if(g_errorcall!=0) g_errorcall(2,deviceInfo.cam_no,1,2,"startdecode",3); charstr_decode[40]; sprintf(str_decode,"cam%dstartdecode",cam_no); SLOG1(str_decode); ret=avcodec_decode_video2(pCodecCtx,pFrame,&got_picture,packet); if(ret<0){ dec_error_count++; charstr3[80]; sprintf(str3,"%d%sdecode_error:%derror_count%d",cam_no,"DecodeError",ret,dec_error_count); SLOG1(str3); if(g_errorcall!=0) g_errorcall(1,deviceInfo.cam_no,0,2,str3,80); printf("cam:%dDecodeErrorgot_picture%ddecode_error_num%d\n",cam_no,got_picture,dec_error_count); if(dec_error_count>2){ dec_error_count=0; //restartffmpeg av_free_packet(packet); Sleep(50); sws_freeContext(img_convert_ctx); img_convert_ctx=NULL; printf("cam%dsws_freeContext1\n",cam_no); //av_free(out_buffer); //av_free(pFrameYUV); avcodec_close(pCodecCtx); //pCodecCtx=NULL; if(avcodec_open2(pCodecCtx,pCodec,NULL)<0){ printf("Couldnotopencodec.\n"); return-1; } /*pFrame=av_frame_alloc(); pFrameYUV=av_frame_alloc();*/ //packet=(AVPacket*)av_malloc(sizeof(AVPacket)); printf("cam_no%davcodec_open2okwidth:%dheight:%d\n",cam_no,pCodecCtx->width,pCodecCtx->height); img_convert_ctx=sws_getContext(pCodecCtx->width,pCodecCtx->height,pCodecCtx->pix_fmt,pCodecCtx->width,pCodecCtx->height,AV_PIX_FMT_RGB24,SWS_BICUBIC,NULL,NULL,NULL); charstr3[40]; sprintf(str3,"ffmpegrestartcam%d",cam_no); SLOG1(str3); continue; } } if(got_picture){ if(g_errorcall!=0) g_errorcall(2,deviceInfo.cam_no,1,2,"got_picture",4); charstr3[40]; sprintf(str3,"cam%dgot_picture",cam_no); SLOG1(str3); sws_scale(img_convert_ctx,(constuint8_t*const*)pFrame->data,pFrame->linesize,0,pCodecCtx->height,pFrameYUV->data,pFrameYUV->linesize); /*fwrite(pFrameYUV->data[0],(pCodecCtx->width)*(pCodecCtx->height)*3,1,output);*/ tcallback((char*)pFrameYUV->data[0],pCodecCtx->height*pCodecCtx->width*3,cam_no,pCodecCtx->height,pCodecCtx->width); } } av_free_packet(packet); Sleep(10); } sws_freeContext(img_convert_ctx); //av_free(out_buffer); av_free(pFrameYUV); avcodec_close(pCodecCtx); avformat_close_input(&pFormatCtx); return0; } inttcp_init(char*ip,intport){ intres=tcpInit(ip,port); //printf("connserver\t%d\n",res); returnres; } intffmpeg_recv(intcam_no,FrameFunctcallback(char*a,intsize,intcam_no,intheight,intwidth)) { av_register_all(); unsignedversion=avcodec_version(); printf("FFmpegversion:%d\n",version); AVFormatContext*pFormatCtx; inti,videoindex; AVCodecContext*pCodecCtx; AVCodec*pCodec; charfilepath[]="video.264"; avformat_network_init(); pFormatCtx=avformat_alloc_context(); //stringpatha="C:\\Users\\sbd01\\Videos\\video.264"; //fp_open=fopen(patha.c_str(),"rb+"); unsignedchar*aviobuffer=(unsignedchar*)av_malloc(1512); AVIOContext*avio=avio_alloc_context(aviobuffer,1512,0,&cam_no,read_buffer,NULL,NULL); pFormatCtx->pb=avio; if(avformat_open_input(&pFormatCtx,NULL,NULL,NULL)!=0){ printf("Couldn'topeninputstream.\n"); return-1; } if(avformat_find_stream_info(pFormatCtx,NULL)<0){ printf("Couldn'tfindstreaminformation.\n"); return-1; } videoindex=-1; for(i=0;i nb_streams;i++) if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO){ videoindex=i; break; } if(videoindex==-1){ printf("Didn'tfindavideostream.\n"); return-1; } pCodecCtx=pFormatCtx->streams[videoindex]->codec; pCodec=avcodec_find_decoder(pCodecCtx->codec_id); if(pCodec==NULL){ printf("Codecnotfound.\n"); return-1; } if(avcodec_open2(pCodecCtx,pCodec,NULL)<0){ printf("Couldnotopencodec.\n"); return-1; } AVFrame*pFrame,*pFrameYUV; pFrame=av_frame_alloc(); pFrameYUV=av_frame_alloc(); intret,got_picture; AVPacket*packet=(AVPacket*)av_malloc(sizeof(AVPacket)); structSwsContext*img_convert_ctx; img_convert_ctx=sws_getContext(pCodecCtx->width,pCodecCtx->height,pCodecCtx->pix_fmt,pCodecCtx->width,pCodecCtx->height,AV_PIX_FMT_RGB24,SWS_BICUBIC,NULL,NULL,NULL); uint8_t*out_buffer; out_buffer=newuint8_t[avpicture_get_size(AV_PIX_FMT_RGB24,pCodecCtx->width,pCodecCtx->height)]; avpicture_fill((AVPicture*)pFrameYUV,out_buffer,AV_PIX_FMT_RGB24,pCodecCtx->width,pCodecCtx->height); while(av_read_frame(pFormatCtx,packet)>=0){ if(packet->stream_index==videoindex){ ret=avcodec_decode_video2(pCodecCtx,pFrame,&got_picture,packet); if(ret<0){ printf("DecodeError.\n"); return-1; } if(got_picture){ sws_scale(img_convert_ctx,(constuint8_t*const*)pFrame->data,pFrame->linesize,0,pCodecCtx->height,pFrameYUV->data,pFrameYUV->linesize); /*fwrite(pFrameYUV->data[0],(pCodecCtx->width)*(pCodecCtx->height)*3,1,output);*/ tcallback((char*)pFrameYUV->data[0],pCodecCtx->height*pCodecCtx->width*3,cam_no,pCodecCtx->height,pCodecCtx->width); } } av_free_packet(packet); } sws_freeContext(img_convert_ctx); //fclose(fp_open); //SDL_Quit(); //av_free(out_buffer); av_free(pFrameYUV); avcodec_close(pCodecCtx); avformat_close_input(&pFormatCtx); return0; } //Callback intfile_buffer(void*opaque,uint8_t*buf,intbuf_size){ FILE*fp_open=(FILE*)opaque; if(!feof(fp_open)){ inttrue_size=fread(buf,1,buf_size,fp_open); returntrue_size; } else{ return-1; } } intplay_file(char*file_name,FrameFunctcallback(char*a,intsize,intnum,intheight,intwidth)) { av_register_all(); unsignedversion=avcodec_version(); printf("FFmpegversion:%d\n",version); AVFormatContext*pFormatCtx; inti,videoindex; AVCodecContext*pCodecCtx; AVCodec*pCodec; charfilepath[]="video.264"; //av_register_all(); avformat_network_init(); pFormatCtx=avformat_alloc_context(); stringpatha="C:\\Users\\sbd01\\Videos\\video.264"; //patha="C:\\Users\\sbd01\\Pictures\\ffmpegtest\\Debug\\video.dat"; FILE*fp_open=fopen(file_name,"rb+"); unsignedchar*aviobuffer=(unsignedchar*)av_malloc(32768); //printf("avio_alloc_context%d\n",cam_no); AVIOContext*avio=avio_alloc_context(aviobuffer,32768,0,(void*)fp_open,file_buffer,NULL,NULL); pFormatCtx->pb=avio; //if(avformat_open_input(&pFormatCtx,patha.c_str(),NULL,NULL)!=0){ if(avformat_open_input(&pFormatCtx,NULL,NULL,NULL)!=0){ printf("Couldn'topeninputstream.\n"); return-1; } if(avformat_find_stream_info(pFormatCtx,NULL)<0){ printf("Couldn'tfindstreaminformation.\n"); return-1; } videoindex=-1; for(i=0;i nb_streams;i++) if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO){ videoindex=i; break; } if(videoindex==-1){ printf("Didn'tfindavideostream.\n"); return-1; } pCodecCtx=pFormatCtx->streams[videoindex]->codec; pCodec=avcodec_find_decoder(pCodecCtx->codec_id); if(pCodec==NULL){ printf("Codecnotfound.\n"); return-1; } if(avcodec_open2(pCodecCtx,pCodec,NULL)<0){ printf("Couldnotopencodec.\n"); return-1; } AVFrame*pFrame,*pFrameYUV; pFrame=av_frame_alloc(); pFrameYUV=av_frame_alloc(); /*if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO|SDL_INIT_TIMER)){ printf("CouldnotinitializeSDL-%s\n",SDL_GetError()); return-1; }*/ /*intscreen_w=0,screen_h=0; SDL_Surface*screen; screen_w=pCodecCtx->width; screen_h=pCodecCtx->height; screen=SDL_SetVideoMode(screen_w,screen_h,0,0); if(!screen){ printf("SDL:couldnotsetvideomode-exiting:%s\n",SDL_GetError()); return-1; } SDL_Overlay*bmp; bmp=SDL_CreateYUVOverlay(pCodecCtx->width,pCodecCtx->height,SDL_YV12_OVERLAY,screen); SDL_Rectrect; rect.x=0; rect.y=0; rect.w=screen_w; rect.h=screen_h;*/ //SDLEnd------------------------ intret,got_picture; AVPacket*packet=(AVPacket*)av_malloc(sizeof(AVPacket)); structSwsContext*img_convert_ctx; img_convert_ctx=sws_getContext(pCodecCtx->width,pCodecCtx->height,pCodecCtx->pix_fmt,pCodecCtx->width,pCodecCtx->height,AV_PIX_FMT_RGB24,SWS_BICUBIC,NULL,NULL,NULL); uint8_t*out_buffer; out_buffer=newuint8_t[avpicture_get_size(AV_PIX_FMT_RGB24,pCodecCtx->width,pCodecCtx->height)]; avpicture_fill((AVPicture*)pFrameYUV,out_buffer,AV_PIX_FMT_RGB24,pCodecCtx->width,pCodecCtx->height); while(av_read_frame(pFormatCtx,packet)>=0){ if(packet->stream_index==videoindex){ ret=avcodec_decode_video2(pCodecCtx,pFrame,&got_picture,packet); if(ret<0){ printf("DecodeError.\n"); return-1; } if(got_picture){ sws_scale(img_convert_ctx,(constuint8_t*const*)pFrame->data,pFrame->linesize,0,pCodecCtx->height,pFrameYUV->data,pFrameYUV->linesize); /*fwrite(pFrameYUV->data[0],(pCodecCtx->width)*(pCodecCtx->height)*3,1,output);*/ tcallback((char*)pFrameYUV->data[0],pCodecCtx->height*pCodecCtx->width*3,1,pCodecCtx->height,pCodecCtx->width); } } av_free_packet(packet); } sws_freeContext(img_convert_ctx); //fclose(fp_open); //SDL_Quit(); //av_free(out_buffer); av_free(pFrameYUV); avcodec_close(pCodecCtx); avformat_close_input(&pFormatCtx); return0; }
以上这篇pythonopencv图片编码为h264文件的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。