다음의 강의를 공부하기 위해 실습한 내용입니다.

www.inflearn.com/course/pandas-%ED%8C%AC%EB%8D%94%EC%8A%A4-%EB%8D%B0%EC%9D%B4%ED%84%B0%EB%B6%84%EC%84%9D-%EA%B8%B0%EC%B4%88/dashboard

 

 

1. Pandas로 csv파일 읽는 법

import pandas as pd

data_frame = pd.read_csv('data/friend_list.csv', delimiter = ',')

data_frame

  - pandas는 numpy를 이용한다.

 

2. Column Name이 없어서 넣어줄 때

import pandas as pd

data_frame = pd.read_csv('data/friend_list_noheader.csv', delimiter = ',', header=None, names=['name','age','job'])

data_frame

 

3. Data Frame의 컬림은 Series로 구성되어 있다.(리스트로 넣으면 된다)

  - pandas.core.series.Series

import pandas as pd

series1 = pd.core.series.Series([1,2,3])
series2 = pd.core.series.Series(['1','2','3'])
series3 = pd.core.series.Series([4,5,6])
series4 = pd.core.series.Series(['a','b','c'])

pd.DataFrame(data=dict(s1=series1, s2=series2, s3=series3, s4=series4))

4. Dictionary 와 Ordered Dictionary를 이용한 DataFrame 생성

import pandas as pd

friend_pd_list =[
    {'name' : 'John', 'age' : 25, 'job' : 'student'},
    {'name' : 'Baek', 'age' : 47, 'job' : 'worker'}
]

df = pd.DataFrame(friend_pd_list)
df


#기호를 잘 봐야 한다.
friend_ordered_dict =OrderedDict(
[
    ('name' , ['John', 'Baek']),
    ('age' , [25, 46]),
    ('job' , ['student', 'worker'])
])

df = pd.DataFrame(friend_ordered_dict)
df

 

//리턴 값
//Little Endian : true
//Big Endian : false

private bool NetworkByteOrderChecker()
{
    ushort[] testUVal = { 0x1234 };
    byte[]   testBVal = new byte[2];
    Buffer.BlockCopy(testUVal, 0, testBVal, 0, 2);

    if (testBVal[0] == 0x34)
        return true;
        
    return false;
}

내 컴퓨터의 바이트 오더를 확인하기 위한 코드

 

네트워크 바이트(빅 엔디안)로 보내기 위해서는 뒤집어야 하나 말아야 하나 flag를 저장하기 위한 함수

 

 

'기타' 카테고리의 다른 글

jetson board Performance  (0) 2021.03.25
Jetson Xavier boot from SSD  (0) 2021.03.24
C# Bitmap객체를 8bit gray로 byte array에 담기  (0) 2021.02.05
Jetson TX2(5)  (0) 2020.05.27
Jetson TX2(4) - Tensorflow install  (0) 2020.05.27

아직까지 파이썬이 익숙하지 않은 관계로...

 

간단한 그래프 그리려고 해도 검색을.... 귀찮음...

 

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 6.3, 0.1) #0에서 6.3까지 0.1 단위로
y1 = np.sin(x)
y2 = np.cos(x)

#그래프 그리기
plt.plot(x, y1, label="sin")
plt.plot(x, y2, linestyle-"--", label="cos") #cos 함수는 점선으로
plt.xlabel("x") #x축 이름
plt.ylabel("y") #y축 이름
plt.title('sin & cos') # 제목
plt.legend()
plt.show()

맞는지 검증은 차차하기로...-_-;

 

 

 

        public static byte[] ToGrayscale(Bitmap bmp)
        {

            int bpp = Image.GetPixelFormatSize(bmp.PixelFormat) / 8;

            BitmapData src_data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, bmp.PixelFormat);

            byte[] src_bytes = new byte[src_data.Stride * src_data.Height];
            Marshal.Copy(src_data.Scan0, src_bytes, 0, src_bytes.Length);
            // Copy the bytes from the image into a byte array
            byte[] dst_bytes = new byte[bmp.Height * bmp.Width];

            for(int i=0; i<dst_bytes.Length; ++i)
                dst_bytes[i] = (byte)((src_bytes[i * bpp + 0] + src_bytes[i * bpp + 1] + src_bytes[i * bpp + 2]) / 3);

            bmp.UnlockBits(src_data);
#if DEBUG
/*
            Bitmap result = new Bitmap(bmp.Width, bmp.Height, PixelFormat.Format8bppIndexed);
            BitmapData dst_data = result.LockBits(new Rectangle(0, 0, result.Width, result.Height), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
            Marshal.Copy(dst_bytes, 0, dst_data.Scan0, dst_bytes.Length);
            result.UnlockBits(dst_data);
            ColorPalette Palette = result.Palette;
            for (int i = 0; i < Palette.Entries.Length; ++i)
            {
                Palette.Entries[i] = Color.FromArgb(i, i, i);
            }
            result.Palette = Palette;

            result.Save("dst.jpg");
//*/
#endif


            return dst_bytes;
        }

'기타' 카테고리의 다른 글

Jetson Xavier boot from SSD  (0) 2021.03.24
내 컴퓨터 바이트 오더 확인하기  (0) 2021.03.05
Jetson TX2(5)  (0) 2020.05.27
Jetson TX2(4) - Tensorflow install  (0) 2020.05.27
Jetson TX2 설정(3)  (0) 2020.05.27

케라스를 잘 하지는 못하지만...-_-;

 

케라스 Convolution 하는 중간에 데이터가

 

(1, 30, 30, 96)

(1, 14, 14, 96)

(1, 6, 6, 384)

 

이런 형태로 나오던데,

 

필터수가 마지막에 나오는 걸로 알고 있는데,

 

이미지화 하려면

(1, 30, 30, 96) -> (96, 30, 30)

이렇게 바꿔야 할듯

 

import numpy as np
from PIL import Image


''' 이놈으로 표현되어야 할 듯 : 
v = np.array(np.uint8(
[
  [[0, 0, 0],[50, 50, 50], [100, 100, 100]], 
  [[100, 100, 100],[150, 150, 150], [200, 200, 200]]
]
))
#'''

v = np.array(np.uint8(
[
  [[[  0, 100], [  0, 100], [  0, 100]], 
   [[ 50, 150], [ 50, 150], [ 50, 150]], 
   [[100, 200], [100, 200], [100, 200]]]
]))

#'''
for i in range(v.shape[len(v.shape)-1]):
    vt = v[...,i]
    print('v.shape-2['+str(i)+'] : ', vt.shape)
    print(vt)
    im = Image.fromarray(vt[0], 'L')
    im.save('image'+str(i)+'.png')
#'''

 

 

출력 결과

v.shape-1 :  (1, 3, 3, 2)
[[[[  0 100]
   [  0 100]
   [  0 100]]

  [[ 50 150]
   [ 50 150]
   [ 50 150]]

  [[100 200]
   [100 200]
   [100 200]]]]

v.shape-2[0] :  (1, 3, 3)
[[[  0   0   0]
  [ 50  50  50]
  [100 100 100]]]

v.shape-2[1] :  (1, 3, 3)
[[[100 100 100]
  [150 150 150]
  [200 200 200]]]

tensorflow 1.15.0

keras 2.3.1

# -*- coding: utf-8 -*-
import os
import numpy as np
from keras.preprocessing import image


X = []
Y = []
filenames = []
z = 0

dataset_dir = 'D:/DataDir/'

print(os.walk(dataset_dir))

for subdir, dirs, files in os.walk(dataset_dir):
    print('subdir : ', subdir, 'dirs : ', dirs)
    for f_path in files[:]:
        if f_path.endswith('png'):
            img = image.load_img(os.path.join(subdir, f_path),
                                     #target_size=None,
                                     target_size=(128, 128),
                                     # grayscale=True, color_mode='rgb')
                                     color_mode='grayscale')
            #print(type(img))
            img = image.img_to_array(img)
            #print(type(img))
            img = img/255.0
            X.append(img)
            #print(type(X))


print(type(X), len(X))
X = np.array(X)
print(type(X), X.shape)
X = X.reshape((X.shape[0], -1))
print(type(X), X.shape)

 

** 결과

<class 'list'> 1512
<class 'numpy.ndarray'> (1512, 256, 256, 1)
<class 'numpy.ndarray'> (1512, 65536)

import os
import shutil

path = 'D:/Yolo/darknet/build/darknet/x64/model/fuelhole04_combo'
train_txt = os.path.join(path, 'train.txt')
test_txt  = os.path.join(path, 'test.txt')

f = open(train_txt)
lines = f.readlines()
f.close()
#os.remove(train_txt)

f_train = open(train_txt, mode='wt', encoding='utf-8')
f_test  = open(test_txt, mode='wt', encoding='utf-8')

for i in range(len(lines)):
    if i % 10 == 0:
        f_test.write(lines[i])
    else:
        f_train.write(lines[i])


train.txt에 있는 파일 내용을

 

train.txt 90%, test.txt 10%의 비율로 나누기

 

 

C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\Remote Debugger\x64

 

그만 좀 까먹자 -_-;

import cv2
import os

index = 0
file_list = os.listdir('.')
file_list_jpg = [file for file in file_list if file.endswith(".jpg")]
key = 0
chkey = ''

while chkey != 'Q' and chkey != 'q':
    img = cv2.imread(file_list_jpg[index], cv2.IMREAD_COLOR)
    cv2.imshow('image', img)
    key = cv2.waitKey(0)
    chkey = chr(key)
    #print('key : ', key, chr(key))
    if chkey == 'n':
        index = index + 1
        if index >= len(file_list_jpg):
            index = 0
    elif chkey == 'p':
        index = index - 1
        if index < 0:
            index = len(file_list_jpg) - 1
    print(index, len(file_list_jpg))        


cv2.destroyAllWindows() 

매번 새로 만드는게 귀찮아서 ...

 

 

+ Recent posts