• Tistory
    • 태그
    • 위치로그
    • 방명록
    • 관리자
    • 글쓰기
Carousel 01
Carousel 02
Previous Next

'Programming'에 해당되는 글 147건

  • 2023.11.08 conda 설치 후 activate가 안될때 문제를 해결하자 1
  • 2023.09.22 [Python] Anaconda 대신 Miniconda로 라이센스 문제를 해결하자
  • 2023.09.13 ffmpeg loading shared libraries error를 해결하자
  • 2023.08.24 [Python] python3을 기본 python으로 사용하기
  • 2023.08.24 [WSL2] 경로를 windows 탐색기에서 확인하자.
  • 2023.07.31 module 'distutils' has no attribute 'version' 에러를 해결하자
  • 2022.11.01 No module named '_overlapped' 문제를 해결하자 1
  • 2022.09.02 skvideo vread 시 FFmpeg 관련 에러를 해결하자
  • 2022.08.29 conda 사용중 "An HTTP error occurred" 가 발생할 경우
  • 2022.08.02 windows terminal(powershell) 에서도 conda를 사용하자
  • 2022.07.06 vscode terminal 에 conda를 연결하자
  • 2022.07.06 vscode에 conda 가상환경을 연결하자.
  • 2022.07.06 vscode keymap을 변경하자
  • 2022.05.09 골뱅이 연산자의 의미 (행렬곱).
  • 2022.03.16 예쁘게 출력하자 pprint - pretty print
  • 2022.02.07 이미지 실제 파일 포맷 확인하기
  • 2022.01.20 warning 을 on/off 하자
  • 2021.12.06 [Git] github -> gitlab / repository를 이사하자
  • 2021.11.30 [ROS] Rosbag2Video
  • 2021.10.06 python version에 따른 pickle 버전 정리

conda 설치 후 activate가 안될때 문제를 해결하자

Programming/Python 2023. 11. 8. 14:57




conda 설치 후 create 로 가상환경 생성까지는 정상적으로 잘 동작했으나

생성 이후 activate 하려하니 아래와 같은 에러를 뿜으며 동작하지 않는 현상을 확인.

 

conda: error: argument COMMAND: invalid choice: 'activate' (choose from 'clean', 'compare', .....(이하생략) .....

 

이럴 때 정상 사용을 위한 방법은 매우 간단했다. 

 


1. conda init

conda init <shell-name> # e.g., zsh or bash

 

2. shell 재시작

3. 정상동작, 끝. 

저작자표시 (새창열림)

'Programming > Python' 카테고리의 다른 글

[Python] Anaconda 대신 Miniconda로 라이센스 문제를 해결하자  (0) 2023.09.22
ffmpeg loading shared libraries error를 해결하자  (0) 2023.09.13
[Python] python3을 기본 python으로 사용하기  (0) 2023.08.24
module 'distutils' has no attribute 'version' 에러를 해결하자  (0) 2023.07.31
No module named '_overlapped' 문제를 해결하자  (1) 2022.11.01
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

,

[Python] Anaconda 대신 Miniconda로 라이센스 문제를 해결하자

Programming/Python 2023. 9. 22. 09:55




Anaconda 의 경우 회사의 규모가 커지면 라이센스 문제가 생기게 되었다..

이 경우 Miniconda 와 conda-forge 채널을 이용하여 라이센스 문제를 해결할 수 있기에 추후 재설치시를 위한 정리


1. Miniconda 설치

2. Channel 설정

conda config --add channels conda-forge
conda config --set channel_priority strict
conda config --remove channels defaults

# 확인용
conda config --show channels

 

(추가) 가상환경의 경우 예전에는 AnacondaPath\envs 에 생성되었으나

이제는 users\.conda\envs 에 생성되어 Anaconda -> Miniconda로 변경해야 될 때 가상환경 관련해서는 

따로 수정하지 않아도 그대로 활용 가능하다.

 

참고출처 : https://devocean.sk.com/blog/techBoardDetail.do?ID=164615

저작자표시 (새창열림)

'Programming > Python' 카테고리의 다른 글

conda 설치 후 activate가 안될때 문제를 해결하자  (1) 2023.11.08
ffmpeg loading shared libraries error를 해결하자  (0) 2023.09.13
[Python] python3을 기본 python으로 사용하기  (0) 2023.08.24
module 'distutils' has no attribute 'version' 에러를 해결하자  (0) 2023.07.31
No module named '_overlapped' 문제를 해결하자  (1) 2022.11.01
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

,

ffmpeg loading shared libraries error를 해결하자

Programming/Python 2023. 9. 13. 17:31




 

"ffmpeg error while loading shared libraries libopenh264.so.5 cannot open shared object file"

 

위와같은 에러를 만났다.. 이럴 경우 해결방법 두가지..


1. ffmpeg 대신 ffmpeg-python 패키지 사용

패키지 중에 ffmpeg 이란놈이 있고 ffmpeg-python 이란 놈이 있던데 내부 구현까지는 모르겠고..

ffmpeg 이 보통 pytorch의 torchvision과 함께 설치되는데 torchvision과 관련된 이슈가 아니라면 

둘 다 설치되어 있을경우나 ffmpeg 만 설치되어 있는경우 기존의 패키지를 삭제하고 

ffmpeg-python 패키지를 설치하여 사용하면 해결 될 수도 있다.

 

2. ffmpeg update

기존에 설치되어 있던 ffmpeg 버전에 따른 이슈로 update를 통해 판올림을 해주면 해결될 수도 있다

나의 경우는 이 방법으로 문제가 해결되었다. 

저작자표시 (새창열림)

'Programming > Python' 카테고리의 다른 글

conda 설치 후 activate가 안될때 문제를 해결하자  (1) 2023.11.08
[Python] Anaconda 대신 Miniconda로 라이센스 문제를 해결하자  (0) 2023.09.22
[Python] python3을 기본 python으로 사용하기  (0) 2023.08.24
module 'distutils' has no attribute 'version' 에러를 해결하자  (0) 2023.07.31
No module named '_overlapped' 문제를 해결하자  (1) 2022.11.01
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

,

[Python] python3을 기본 python으로 사용하기

Programming/Python 2023. 8. 24. 14:47




ubuntu에서 python을 실행하면 python command를 찾지 못했다는 얘기를 할 떄가 있다

그럴 경우 python2 / python3 과 같이 버전을 명시해주면 되긴 하지만.. 요즘 python2를 쓸일이 거의 없지..

 

python3을 기본 python으로 설정하는 방법 정리

 


1. alias 로 설정하기

vim ~/.bashrc
alias python=python3
:wq # 저장 후 종료
source ~/.bashrc

 

2. 패키지 설치

sudo apt install python-is-python3

 

 

저작자표시 (새창열림)

'Programming > Python' 카테고리의 다른 글

[Python] Anaconda 대신 Miniconda로 라이센스 문제를 해결하자  (0) 2023.09.22
ffmpeg loading shared libraries error를 해결하자  (0) 2023.09.13
module 'distutils' has no attribute 'version' 에러를 해결하자  (0) 2023.07.31
No module named '_overlapped' 문제를 해결하자  (1) 2022.11.01
skvideo vread 시 FFmpeg 관련 에러를 해결하자  (0) 2022.09.02
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

,

[WSL2] 경로를 windows 탐색기에서 확인하자.

Programming/기타 etc. 2023. 8. 24. 13:38




wsl2 에서는 explorer.exe 명령어가 동작한다. 

파라미터로 경로를 입력하면 해당 경로가 파일 탐색기로 바로 열리기에 현재 경로를 파라미터로 넣어 바로 열수 있다.

 


explorer.exe .
저작자표시 (새창열림)

'Programming > 기타 etc.' 카테고리의 다른 글

conda 사용중 "An HTTP error occurred" 가 발생할 경우  (0) 2022.08.29
[Git] github -> gitlab / repository를 이사하자  (0) 2021.12.06
[ROS] Rosbag2Video  (0) 2021.11.30
float 값의 비교 (== 연산자는 위험하다!)  (0) 2021.04.13
google drive web client 사용량 제한  (0) 2021.02.25
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

,

module 'distutils' has no attribute 'version' 에러를 해결하자

Programming/Python 2023. 7. 31. 16:43




module 'distutils' has no attribute 'version' 에러 가 가끔 발생하는 경우가 있는데.. 

 

이 경우는 setuptools 라이브러리 버전 문제로 특정 버전으로 설치를 해주면 간단히 해결할 수 있다.

 


$ pip install setuptools==59.5.0

 

이 버전으로 다시 설치해주면 문제없이 동작 가능.. 

저작자표시 (새창열림)

'Programming > Python' 카테고리의 다른 글

ffmpeg loading shared libraries error를 해결하자  (0) 2023.09.13
[Python] python3을 기본 python으로 사용하기  (0) 2023.08.24
No module named '_overlapped' 문제를 해결하자  (1) 2022.11.01
skvideo vread 시 FFmpeg 관련 에러를 해결하자  (0) 2022.09.02
windows terminal(powershell) 에서도 conda를 사용하자  (0) 2022.08.02
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

,

No module named '_overlapped' 문제를 해결하자

Programming/Python 2022. 11. 1. 10:52




파이썬 프로젝트를 사용하던 중 잘 돌아가던 프로젝트인데 갑자기 

"No module named '_overlapped'" 에러가 발생한 것을 확인했다.

 

이는 vscode에서 자동으로 생성한 코드 때문에 발생 한 문제로 확인됨..

NULL을 사용할 경우 vscode 가 자동으로 코드 상단에

"from asyncio.windows_events import NULL" 를 추가하는데 이놈이 문제가 된다.

 

해결 방법은 간단하게 자동으로 추가된 라인을 지우고 사용해도 별다른 이슈는 발생하지 않는다.

 

저작자표시 (새창열림)

'Programming > Python' 카테고리의 다른 글

[Python] python3을 기본 python으로 사용하기  (0) 2023.08.24
module 'distutils' has no attribute 'version' 에러를 해결하자  (0) 2023.07.31
skvideo vread 시 FFmpeg 관련 에러를 해결하자  (0) 2022.09.02
windows terminal(powershell) 에서도 conda를 사용하자  (0) 2022.08.02
vscode terminal 에 conda를 연결하자  (0) 2022.07.06
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

,

skvideo vread 시 FFmpeg 관련 에러를 해결하자

Programming/Python 2022. 9. 2. 14:16




skvideo.io 를 사용하던 도중 

AssertionError: Cannot find installation of real FFmpeg (which comes with ffprobe).

vread시 위와 같은 에러를 만났다. 

 

이럴 경우 ffmpeg를 설치해주면 정상적으로 vread를 사용할 수 있다.

 

>> conda install ffmpeg -c mrinaljain17

저작자표시 (새창열림)

'Programming > Python' 카테고리의 다른 글

module 'distutils' has no attribute 'version' 에러를 해결하자  (0) 2023.07.31
No module named '_overlapped' 문제를 해결하자  (1) 2022.11.01
windows terminal(powershell) 에서도 conda를 사용하자  (0) 2022.08.02
vscode terminal 에 conda를 연결하자  (0) 2022.07.06
vscode에 conda 가상환경을 연결하자.  (0) 2022.07.06
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

,

conda 사용중 "An HTTP error occurred" 가 발생할 경우

Programming/기타 etc. 2022. 8. 29. 14:56




conda 사용 중 "An HTTP error occurred when trying to retrieve this URL" 에러가 발생할 경우
 
서버 접속이 차단되어 발생하는 문제라 함.
 
이럴 경우 config 를 수정하여 해결 가능.. 하다는데

$ conda config --set ssl_verify False

(내 경우는 이 방법으로 해결 안됨..해결 후 업데이트 예정.) 

 

저작자표시 (새창열림)

'Programming > 기타 etc.' 카테고리의 다른 글

[WSL2] 경로를 windows 탐색기에서 확인하자.  (0) 2023.08.24
[Git] github -> gitlab / repository를 이사하자  (0) 2021.12.06
[ROS] Rosbag2Video  (0) 2021.11.30
float 값의 비교 (== 연산자는 위험하다!)  (0) 2021.04.13
google drive web client 사용량 제한  (0) 2021.02.25
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

,

windows terminal(powershell) 에서도 conda를 사용하자

Programming/Python 2022. 8. 2. 09:48




일반적으로 command prompt 를 사용하다 powershell을 사용 해 보기 시작했다.

 

그러나 powershell 환경에서는 conda가 적용되어 있지 않아 

powershell 에서 conda를 사용하는 방법을 기록.


0. conda 설치 및 환경변수 설정은 cmd에서 미리 했다고 치고...

 

1. powershell 환경에서 conda init

conda init powershell

2. (관리자모드 필요) 로컬시스템 실행 정책 업데이트

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned

3. powershell 재시작

 

 

저작자표시 (새창열림)

'Programming > Python' 카테고리의 다른 글

No module named '_overlapped' 문제를 해결하자  (1) 2022.11.01
skvideo vread 시 FFmpeg 관련 에러를 해결하자  (0) 2022.09.02
vscode terminal 에 conda를 연결하자  (0) 2022.07.06
vscode에 conda 가상환경을 연결하자.  (0) 2022.07.06
vscode keymap을 변경하자  (0) 2022.07.06
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

,

vscode terminal 에 conda를 연결하자

Programming/Python 2022. 7. 6. 11:07




이전글에서 vscode에 가상환경을 연결하는 것까지는 설정했다.

그러나 ctrl + ` 를 이용하여 터미널을 열 경우 conda가 연결되지 않는 현상이 있어서

터미널에 conda 환경을 연결하는 방법을 기록.

 


 

1. 시스템 환경변수 path 에 conda path 설정

    - {conda root}

    - {conda root}/Library

    - {conda root}/Scripts

 

2. default terminal 변경 (default termianl이 windows powershell인 경우)

    - command palatte - Terminal: Select Default Profile 선택

    - Command Prompt 선택

저작자표시 (새창열림)

'Programming > Python' 카테고리의 다른 글

skvideo vread 시 FFmpeg 관련 에러를 해결하자  (0) 2022.09.02
windows terminal(powershell) 에서도 conda를 사용하자  (0) 2022.08.02
vscode에 conda 가상환경을 연결하자.  (0) 2022.07.06
vscode keymap을 변경하자  (0) 2022.07.06
골뱅이 연산자의 의미 (행렬곱).  (0) 2022.05.09
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

,

vscode에 conda 가상환경을 연결하자.

Programming/Python 2022. 7. 6. 11:03




conda 가상환경을 구축하여 사용중이고 IDE로 pycharm을 주로 사용하다

vscode도 사용하기 위해 설치 후 가상환경을 연결하는 방법을 기록.

 


1. command palette (ctrl + shift + p)

2. Python: Select Interpreter 

3. 사용하고자 하는 가상환경 선택

저작자표시 (새창열림)

'Programming > Python' 카테고리의 다른 글

windows terminal(powershell) 에서도 conda를 사용하자  (0) 2022.08.02
vscode terminal 에 conda를 연결하자  (0) 2022.07.06
vscode keymap을 변경하자  (0) 2022.07.06
골뱅이 연산자의 의미 (행렬곱).  (0) 2022.05.09
예쁘게 출력하자 pprint - pretty print  (0) 2022.03.16
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

,

vscode keymap을 변경하자

Programming/Python 2022. 7. 6. 10:58




기본적으로 vscode keymap이 visual studio와 다른 부분이 있다.

visual studio keymap 에 익숙해진 나로써는 불편한 부분이 있어 keymap 변경을 위한 방법을 기록.

 


 

1. vscode 설치 된 상태에서

2. https://marketplace.visualstudio.com/items?itemName=ms-vscode.vs-keybindings keymap 파일 설치

저작자표시 (새창열림)

'Programming > Python' 카테고리의 다른 글

vscode terminal 에 conda를 연결하자  (0) 2022.07.06
vscode에 conda 가상환경을 연결하자.  (0) 2022.07.06
골뱅이 연산자의 의미 (행렬곱).  (0) 2022.05.09
예쁘게 출력하자 pprint - pretty print  (0) 2022.03.16
이미지 실제 파일 포맷 확인하기  (0) 2022.02.07
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

,

골뱅이 연산자의 의미 (행렬곱).

Programming/Python 2022. 5. 9. 10:17




이전에 파이썬에서 쓰이는 골뱅이는 데코레이터의 역할로 확인했었고 그것만 기억하고 있었다.

골뱅이, DECORATOR를 이용하여 함수 실행시간을 측정하자.

 

골뱅이, decorator를 이용하여 함수 실행시간을 측정하자.

프로그램을 구현하다 보면 특정 기능이 어느정도 시간을 소요하는지 확인이 필요한 경우가 있다. 이럴때 보통 아래와 같이 시간 측정을 위한 code 앞뒤에서 time 라이브러리를 이용하여 시간을 계

jangjy.tistory.com

 

 

이후 코드를 보다 중간에 골뱅이가 쓰인것을 보고 찾아본 다른 사용법.

 


@ 연산자는 numpy에서 matmul 또는 dot와 같은 역할을 한다.

즉, 행렬곱을 계산하는 연산자이다.

 

asterisk로 표현되는 element-wise 곱 연산이 아닌 행렬-행렬간 곱을 계산할때 사용한다.

저작자표시 (새창열림)

'Programming > Python' 카테고리의 다른 글

vscode에 conda 가상환경을 연결하자.  (0) 2022.07.06
vscode keymap을 변경하자  (0) 2022.07.06
예쁘게 출력하자 pprint - pretty print  (0) 2022.03.16
이미지 실제 파일 포맷 확인하기  (0) 2022.02.07
warning 을 on/off 하자  (0) 2022.01.20
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

,

예쁘게 출력하자 pprint - pretty print

Programming/Python 2022. 3. 16. 11:05




딕셔너리, json 등을 print로 찍어 볼 일이 가끔 있는데 

이런 데이터들은 그냥 print로 출력하면 정보가 구분없이 한주롤 쭉 나와서 가독성이 크게 떨어진다

이럴 때 사용가능한 예쁜 출력 - pretty print -> pprint!

 


사용법은 매우 심플하게

pprint 모듈의 pprint를 import 해 준 뒤 print 대신 pprint를 사용하면 된다

 

from pprint import pprint

data = {~~~~블라블라~~~}

# 기존 출력 
print(data)

# 예쁘게 출력
pprint(data)
저작자표시 (새창열림)

'Programming > Python' 카테고리의 다른 글

vscode keymap을 변경하자  (0) 2022.07.06
골뱅이 연산자의 의미 (행렬곱).  (0) 2022.05.09
이미지 실제 파일 포맷 확인하기  (0) 2022.02.07
warning 을 on/off 하자  (0) 2022.01.20
python version에 따른 pickle 버전 정리  (0) 2021.10.06
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

,

이미지 실제 파일 포맷 확인하기

Programming/Python 2022. 2. 7. 13:01




이미지 파일을 사용하다 보면 파일명의 확장자와 실제 이미지의 포맷이 다른 경우가 가끔 있다.

 

이런 파일을 확인하기 위한 방법 정리.


파이썬의 PIL-Image 모듈을 이용하면 쉽게 실제 포맷을 확인 할 수 있다.

 

from PIL import Image
 
img = Image.open("sample01.jpg")
img.format

>> 'GIF' 
# 이 경우 파일명 확장자는 jpg 이나 실제 이미지 포맷은 gif인 경우.

 

실제 정보를 확인 한 후 적절한 처리를 하고 사용하면 된다.

저작자표시 (새창열림)

'Programming > Python' 카테고리의 다른 글

골뱅이 연산자의 의미 (행렬곱).  (0) 2022.05.09
예쁘게 출력하자 pprint - pretty print  (0) 2022.03.16
warning 을 on/off 하자  (0) 2022.01.20
python version에 따른 pickle 버전 정리  (0) 2021.10.06
pycharm 에서 인덱싱 제외 폴더를 설정하자  (0) 2021.08.06
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

,

warning 을 on/off 하자

Programming/Python 2022. 1. 20. 15:16




외부 라이브러리들을 사용하다보면 여러 이유로 warning이 발생하곤 한다

정보 전달을 목적으로 경고를 띄워주는 것이긴 하지만 

release 상태에서는 경고 없이 실행한 결과만 보고싶을 때 아래와 같이 경고를 끄는것이 가능하다

 


import warnings

# warning off
warnings.filterwarnings("ignore")

# warning on
warnings.filterwarnings("default")
저작자표시 (새창열림)

'Programming > Python' 카테고리의 다른 글

예쁘게 출력하자 pprint - pretty print  (0) 2022.03.16
이미지 실제 파일 포맷 확인하기  (0) 2022.02.07
python version에 따른 pickle 버전 정리  (0) 2021.10.06
pycharm 에서 인덱싱 제외 폴더를 설정하자  (0) 2021.08.06
string 앞에 0 또는 문자를 삽입하여 길이를 맞추자  (0) 2021.07.02
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

,

[Git] github -> gitlab / repository를 이사하자

Programming/기타 etc. 2021. 12. 6. 14:22




모종의 이유로 guthub 의 repository를 gitlab으로 옮겨야 할 경우가 있다

코드 clone 후 저장소 바꿔서 push 하는 방법도 있겠지만 더 간단한 방법이 있어서 정리

 


[1단계. github에서]

1. settings - Developer Settings - Personal access tokens

2. scrops 선택(repo 정도로 사용) 후 Generate Token

 

[2단계. gitlab에서]

1. New project - Import project - Github

2. Personal Access Token에 1의 token 붙여넣기 - List your Github repositories

3. list 중 필요한 repository 우측의 import 로 추가

저작자표시 (새창열림)

'Programming > 기타 etc.' 카테고리의 다른 글

[WSL2] 경로를 windows 탐색기에서 확인하자.  (0) 2023.08.24
conda 사용중 "An HTTP error occurred" 가 발생할 경우  (0) 2022.08.29
[ROS] Rosbag2Video  (0) 2021.11.30
float 값의 비교 (== 연산자는 위험하다!)  (0) 2021.04.13
google drive web client 사용량 제한  (0) 2021.02.25
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

,

[ROS] Rosbag2Video

Programming/기타 etc. 2021. 11. 30. 16:42




ROS 에서 녹화된 rosbag 파일 내의 비디오를 추출하는 코드

github에 쓰기 편하게 만들어 준 코드가 있어서 기록.

 

https://github.com/mlaiacker/rosbag2video

 

GitHub - mlaiacker/rosbag2video: converts image sequence in ros bag files to video files

converts image sequence in ros bag files to video files - GitHub - mlaiacker/rosbag2video: converts image sequence in ros bag files to video files

github.com

 

#!/usr/bin/env python3

"""
rosbag2video.py
rosbag to video file conversion tool
by Abel Gabor 2019
baquatelle@gmail.com
requirements:
sudo apt install python3-roslib python3-sensor-msgs python3-opencv ffmpeg
based on the tool by Maximilian Laiacker 2016
post@mlaiacker.de"""

import roslib
#roslib.load_manifest('rosbag')
import rospy
import rosbag
import sys, getopt
import os
from sensor_msgs.msg import CompressedImage
from sensor_msgs.msg import Image
import cv2

import numpy as np

import shlex, subprocess

MJPEG_VIDEO = 1
RAWIMAGE_VIDEO = 2
VIDEO_CONVERTER_TO_USE = "ffmpeg" # or you may want to use "avconv"

def print_help():
    print('rosbag2video.py [--fps 25] [--rate 1] [-o outputfile] [-v] [-s] [-t topic] bagfile1 [bagfile2] ...')
    print()
    print('Converts image sequence(s) in ros bag file(s) to video file(s) with fixed frame rate using',VIDEO_CONVERTER_TO_USE)
    print(VIDEO_CONVERTER_TO_USE,'needs to be installed!')
    print()
    print('--fps   Sets FPS value that is passed to',VIDEO_CONVERTER_TO_USE)
    print('        Default is 25.')
    print('-h      Displays this help.')
    print('--ofile (-o) sets output file name.')
    print('        If no output file name (-o) is given the filename \'<prefix><topic>.mp4\' is used and default output codec is h264.')
    print('        Multiple image topics are supported only when -o option is _not_ used.')
    print('        ',VIDEO_CONVERTER_TO_USE,' will guess the format according to given extension.')
    print('        Compressed and raw image messages are supported with mono8 and bgr8/rgb8/bggr8/rggb8 formats.')
    print('--rate  (-r) You may slow down or speed up the video.')
    print('        Default is 1.0, that keeps the original speed.')
    print('-s      Shows each and every image extracted from the rosbag file (cv_bride is needed).')
    print('--topic (-t) Only the images from topic "topic" are used for the video output.')
    print('-v      Verbose messages are displayed.')
    print('--prefix (-p) set a output file name prefix othervise \'bagfile1\' is used (if -o is not set).')
    print('--start Optional start time in seconds.')
    print('--end   Optional end time in seconds.')



class RosVideoWriter():
    def __init__(self, fps=25.0, rate=1.0, topic="", output_filename ="", display= False, verbose = False, start = rospy.Time(0), end = rospy.Time(sys.maxsize)):
        self.opt_topic = topic
        self.opt_out_file = output_filename
        self.opt_verbose = verbose
        self.opt_display_images = display
        self.opt_start = start
        self.opt_end = end
        self.rate = rate
        self.fps = fps
        self.opt_prefix= None
        self.t_first={}
        self.t_file={}
        self.t_video={}
        self.p_avconv = {}

    def parseArgs(self, args):
        opts, opt_files = getopt.getopt(args,"hsvr:o:t:p:",["fps=","rate=","ofile=","topic=","start=","end=","prefix="])
        for opt, arg in opts:
            if opt == '-h':
                print_help()
                sys.exit(0)
            elif opt == '-s':
                self.opt_display_images = True
            elif opt == '-v':
                self.opt_verbose = True
            elif opt in ("--fps"):
                self.fps = float(arg)
            elif opt in ("-r", "--rate"):
                self.rate = float(arg)
            elif opt in ("-o", "--ofile"):
                self.opt_out_file = arg
            elif opt in ("-t", "--topic"):
                self.opt_topic = arg
            elif opt in ("-p", "--prefix"):
                self.opt_prefix = arg
            elif opt in ("--start"):
                self.opt_start = rospy.Time(int(arg))
                if(self.opt_verbose):
                    print("starting at",self.opt_start.to_sec())
            elif opt in ("--end"):
                self.opt_end = rospy.Time(int(arg))
                if(self.opt_verbose):
                    print("ending at",self.opt_end.to_sec())
            else:
                print("opz:", opt,'arg:', arg)

        if (self.fps<=0):
            print("invalid fps", self.fps)
            self.fps = 1

        if (self.rate<=0):
            print("invalid rate", self.rate)
            self.rate = 1

        if(self.opt_verbose):
            print("using ",self.fps," FPS")
        return opt_files


    # filter messages using type or only the opic we whant from the 'topic' argument
    def filter_image_msgs(self, topic, datatype, md5sum, msg_def, header):
        if(datatype=="sensor_msgs/CompressedImage"):
            if (self.opt_topic != "" and self.opt_topic == topic) or self.opt_topic == "":
                print("############# COMPRESSED IMAGE  ######################")
                print(topic,' with datatype:', str(datatype))
                print()
                return True;

        if(datatype=="theora_image_transport/Packet"):
            if (self.opt_topic != "" and self.opt_topic == topic) or self.opt_topic == "":
                print(topic,' with datatype:', str(datatype))
                print('!!! theora is not supported, sorry !!!')
                return False;

        if(datatype=="sensor_msgs/Image"):
            if (self.opt_topic != "" and self.opt_topic == topic) or self.opt_topic == "":
                print("############# UNCOMPRESSED IMAGE ######################")
                print(topic,' with datatype:', str(datatype))
                print()
                return True;

        return False;


    def write_output_video(self, msg, topic, t, video_fmt, pix_fmt = ""):
        # no data in this topic
        if len(msg.data) == 0 :
            return
        # initiate data for this topic
        if not topic in self.t_first :
            self.t_first[topic] = t # timestamp of first image for this topic
            self.t_video[topic] = 0
            self.t_file[topic] = 0
        # if multiple streams of images will start at different times the resulting video files will not be in sync
        # current offset time we are in the bag file
        self.t_file[topic] = (t-self.t_first[topic]).to_sec()
        # fill video file up with images until we reache the current offset from the beginning of the bag file
        while self.t_video[topic] < self.t_file[topic]/self.rate :
            if not topic in self.p_avconv:
                # we have to start a new process for this topic
                if self.opt_verbose :
                    print("Initializing pipe for topic", topic, "at time", t.to_sec())
                if self.opt_out_file=="":
                    out_file = self.opt_prefix + str(topic).replace("/", "_")+".mp4"
                else:
                    out_file = self.opt_out_file

                if self.opt_verbose :
                    print("Using output file ", out_file, " for topic ", topic, ".")

                if video_fmt == MJPEG_VIDEO :
                    cmd = [VIDEO_CONVERTER_TO_USE, '-v', '1', '-stats', '-r',str(self.fps),'-c','mjpeg','-f','mjpeg','-i','-','-an',out_file]
                    self.p_avconv[topic] = subprocess.Popen(cmd, stdin=subprocess.PIPE)
                    if self.opt_verbose :
                        print("Using command line:")
                        print(cmd)
                elif video_fmt == RAWIMAGE_VIDEO :
                    size = str(msg.width)+"x"+str(msg.height)
                    cmd = [VIDEO_CONVERTER_TO_USE, '-v', '1', '-stats','-r',str(self.fps),'-f','rawvideo','-s',size,'-pix_fmt', pix_fmt,'-i','-','-an',out_file]
                    self.p_avconv[topic] = subprocess.Popen(cmd, stdin=subprocess.PIPE)
                    if self.opt_verbose :
                        print("Using command line:")
                        print(cmd)

                else :
                    print("Script error, unknown value for argument video_fmt in function write_output_video.")
                    exit(1)
            # send data to ffmpeg process pipe
            self.p_avconv[topic].stdin.write(msg.data)
            # next frame time
            self.t_video[topic] += 1.0/self.fps

    def addBag(self, filename):
        if self.opt_display_images:
            from cv_bridge import CvBridge, CvBridgeError
            bridge = CvBridge()
            cv_image = []

        if self.opt_verbose :
            print("Bagfile: {}".format(filename))

        if not self.opt_prefix:
            # create the output in the same folder and name as the bag file minu '.bag'
            self.opt_prefix = bagfile[:-4]

        #Go through the bag file
        bag = rosbag.Bag(filename)
        if self.opt_verbose :
            print("Bag opened.")
        # loop over all topics
        for topic, msg, t in bag.read_messages(connection_filter=self.filter_image_msgs, start_time=self.opt_start, end_time=self.opt_end):
            try:
                if msg.format.find("jpeg")!=-1 :
                    if msg.format.find("8")!=-1 and (msg.format.find("rgb")!=-1 or msg.format.find("bgr")!=-1 or msg.format.find("bgra")!=-1 ):
                        if self.opt_display_images:
                            np_arr = np.fromstring(msg.data, np.uint8)
                            cv_image = cv2.imdecode(np_arr, cv2.CV_LOAD_IMAGE_COLOR)
                        self.write_output_video( msg, topic, t, MJPEG_VIDEO )
                    elif msg.format.find("mono8")!=-1 :
                        if self.opt_display_images:
                            np_arr = np.fromstring(msg.data, np.uint8)
                            cv_image = cv2.imdecode(np_arr, cv2.CV_LOAD_IMAGE_COLOR)
                        self.write_output_video( msg, topic, t, MJPEG_VIDEO )
                    elif msg.format.find("16UC1")!=-1 :
                        if self.opt_display_images:
                            np_arr = np.fromstring(msg.data, np.uint16)
                            cv_image = cv2.imdecode(np_arr, cv2.CV_LOAD_IMAGE_COLOR)
                        self.write_output_video( msg, topic, t, MJPEG_VIDEO )
                    else:
                        print('unsupported jpeg format:', msg.format, '.', topic)

            # has no attribute 'format'
            except AttributeError:
                try:
                        pix_fmt=None
                        if msg.encoding.find("mono8")!=-1 or msg.encoding.find("8UC1")!=-1:
                            pix_fmt = "gray"
                            if self.opt_display_images:
                                cv_image = bridge.imgmsg_to_cv2(msg, "bgr8")

                        elif msg.encoding.find("bgra")!=-1 :
                            pix_fmt = "bgra"
                            if self.opt_display_images:
                                cv_image = bridge.imgmsg_to_cv2(msg, "bgr8")

                        elif msg.encoding.find("bgr8")!=-1 :
                            pix_fmt = "bgr24"
                            if self.opt_display_images:
                                cv_image = bridge.imgmsg_to_cv2(msg, "bgr8")
                        elif msg.encoding.find("bggr8")!=-1 :
                            pix_fmt = "bayer_bggr8"
                            if self.opt_display_images:
                                cv_image = bridge.imgmsg_to_cv2(msg, "bayer_bggr8")
                        elif msg.encoding.find("rggb8")!=-1 :
                            pix_fmt = "bayer_rggb8"
                            if self.opt_display_images:
                                cv_image = bridge.imgmsg_to_cv2(msg, "bayer_rggb8")
                        elif msg.encoding.find("rgb8")!=-1 :
                            pix_fmt = "rgb24"
                            if self.opt_display_images:
                                cv_image = bridge.imgmsg_to_cv2(msg, "bgr8")
                        elif msg.encoding.find("16UC1")!=-1 :
                            pix_fmt = "gray16le"
                        else:
                            print('unsupported encoding:', msg.encoding, topic)
                            #exit(1)
                        if pix_fmt:
                            self.write_output_video( msg, topic, t, RAWIMAGE_VIDEO, pix_fmt )

                except AttributeError:
                    # maybe theora packet
                    # theora not supported
                    if self.opt_verbose :
                        print("Could not handle this format. Maybe thoera packet? theora is not supported.")
                    pass
            if self.opt_display_images:
                cv2.imshow(topic, cv_image)
                key=cv2.waitKey(1)
                if key==1048603:
                    exit(1)
        if self.p_avconv == {}:
            print("No image topics found in bag:", filename)
        bag.close()



if __name__ == '__main__':
    #print()
    #print('rosbag2video, by Maximilian Laiacker 2020 and Abel Gabor 2019')
    #print()

    if len(sys.argv) < 2:
        print('Please specify ros bag file(s)!')
        print_help()
        sys.exit(1)
    else :
        videowriter = RosVideoWriter()
        try:
            opt_files = videowriter.parseArgs(sys.argv[1:])
        except getopt.GetoptError:
            print_help()
            sys.exit(2)


    # loop over all files
    for files in range(0,len(opt_files)):
        #First arg is the bag to look at
        bagfile = opt_files[files]
        videowriter.addBag(bagfile)
    print("finished")
저작자표시 (새창열림)

'Programming > 기타 etc.' 카테고리의 다른 글

conda 사용중 "An HTTP error occurred" 가 발생할 경우  (0) 2022.08.29
[Git] github -> gitlab / repository를 이사하자  (0) 2021.12.06
float 값의 비교 (== 연산자는 위험하다!)  (0) 2021.04.13
google drive web client 사용량 제한  (0) 2021.02.25
pycharm 사용 및 환경설정 팁  (0) 2019.03.18
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

,

python version에 따른 pickle 버전 정리

Programming/Python 2021. 10. 6. 16:40




pickle 데이터를 load 할 때 가끔 unsupport protocol 에러를 보는 경우가 있다.

이 경우 dump 한 버전과 load 한 버전이 달라서 발생하는 문제.

 

기본 버전을 확인하기 위해 기록

 


python ver. pickle protocol ver.
1.x 1
2.3~2.7 2
3.0~3.7 3
3.8 4
3.8 5
저작자표시 (새창열림)

'Programming > Python' 카테고리의 다른 글

이미지 실제 파일 포맷 확인하기  (0) 2022.02.07
warning 을 on/off 하자  (0) 2022.01.20
pycharm 에서 인덱싱 제외 폴더를 설정하자  (0) 2021.08.06
string 앞에 0 또는 문자를 삽입하여 길이를 맞추자  (0) 2021.07.02
설치된 라이브러리 리스트를 requirements.txt 로 만들자.  (0) 2021.06.18
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

,
  • «
  • 1
  • 2
  • 3
  • 4
  • ···
  • 8
  • »

카테고리

  • 살다보니.. (449)
    • 주절거림 (3)
    • 취미생활 (36)
      • 지식과 지혜 (3)
      • 풍경이 되어 (4)
      • Memories (17)
      • 엥겔지수를 높여라 (2)
    • mathematics (6)
      • Matrix Computation (2)
      • RandomProcesses (3)
    • English.. (8)
    • Programming (147)
      • C, C++, MFC (51)
      • C# (1)
      • OpenCV (17)
      • Python (58)
      • Git, Docker (3)
      • Matlab (4)
      • Windows (3)
      • Kinect V2 (2)
      • 기타 etc. (8)
    • 전공관련 (80)
      • Algorithm (6)
      • Deep Learning (54)
      • 실습 프로그램 (4)
      • 주워들은 용어정리 (8)
      • 기타 etc. (8)
    • Computer (118)
      • Utility (21)
      • Windows (31)
      • Mac (4)
      • Ubuntu, Linux (58)
      • NAS (2)
      • Embedded, Mobile (2)
    • IT, Device (41)
      • 제품 사용기, 개봉기 (14)
      • 스마트 체험단 신청 (27)
    • Wish List (3)
    • TISTORY TIP (5)
    • 미분류. 수정중 (1)

태그목록

  • 스마트체험단
  • 칼로리 대폭발
  • 딥러닝
  • Computer Tip
  • 크롬
  • 일본
  • Convolutional Neural Networks
  • matlab
  • random variable
  • 큐슈
  • SVM
  • portugal
  • 오봉자싸롱
  • CStdioFile
  • 포르투갈
  • 매트랩 함수
  • 매트랩
  • matlab function
  • function
  • 갤럭시노트3
  • DeepLearning
  • Deep Learning
  • 후쿠오카
  • utility
  • review
  • 에누리닷컴
  • LIBSVM
  • DSLR
  • ColorMeRad
  • ReadString

달력

«   2025/06   »
일 월 화 수 목 금 토
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
06-10 20:52

LATEST FROM OUR BLOG

RSS 구독하기

BLOG VISITORS

  • Total :
  • Today :
  • Yesterday :

Copyright © 2015 Socialdev. All Rights Reserved.

티스토리툴바