워낙 기초가 안되어 있다보니,

 

numpy 변수의 차원을 늘리는 것조차 급하면 생각이 안나서 기록해둠

 

print('test_images[0].shape : ', test_images[0].shape)

expand_dims_val0 = np.expand_dims(test_images[0], axis=0)
print('expand_dims_val0.shape : ', expand_dims_val0.shape)

expand_dims_val1 = np.expand_dims(test_images[0], axis=1)
print('expand_dims_val1.shape : ', expand_dims_val1.shape)

expand_dims_val2 = np.expand_dims(test_images[0], axis=2)
print('expand_dims_val1.shape : ', expand_dims_val2.shape)

print('squeeze_val0.shape : ', np.squeeze(expand_dims_val0).shape)
print('squeeze_val1.shape : ', np.squeeze(expand_dims_val1).shape)
print('squeeze_val2.shape : ', np.squeeze(expand_dims_val2).shape)

 

[결과]

test_images[0].shape :  (28, 28)
expand_dims_val0.shape :  (1, 28, 28)
expand_dims_val1.shape :  (28, 1, 28)
expand_dims_val1.shape :  (28, 28, 1)
squeeze_val0.shape :  (28, 28)
squeeze_val1.shape :  (28, 28)
squeeze_val2.shape :  (28, 28)

'파이썬' 카테고리의 다른 글

그래프의 개형을 그려보자  (0) 2021.04.17
pymodbus test  (0) 2021.03.25
Pandas 관련 이것저것  (0) 2021.03.06
[파이썬] 간단한 그래프 그리기  (0) 2021.02.22
KERAS Convolution 필터 데이터 저장하기  (0) 2020.12.09

흑백 이미지의 히스토그램의 개형을 그려보려고 이래저래 검색하여 테스트 한 결과를 정리하고자 한다

 

** np.polyfit 함수의 마지막 인자가 그래프 형태를 결정하는 인자인듯

 

 

import numpy as np
import cv2
from matplotlib import pyplot as plt

img = cv2.imread('d:/bag/Capture/combo1_Infrared_center_02.png',0)

hist = cv2.calcHist([img],[0],None,[256],[0,256])

x = np.arange(0,256)
hist2 = np.zeros(256);

avg_value = 9
avg_value_2 = int(avg_value/2)

hist = hist.reshape(256)

pf = np.polyfit(x, hist, 1)
p1d = np.poly1d(pf)

plt.figure(figsize=(10,5))
plt.plot(x, hist, label='histogram', color='y')
plt.plot(x, p1d(x), lw=2, color='r', label='polyfit')
plt.grid()
plt.legend()
plt.show()

1) 선형 개형

 

np.polyfit 마지막 인자 : 2

 

np.polyfit 마지막 인자 : 3

 

np.polyfit 마지막 인자 : 4

 

 

 

 

 

 

 

 

 

 

'파이썬' 카테고리의 다른 글

numpy 차원수 늘리기 / 줄이기  (0) 2021.10.28
pymodbus test  (0) 2021.03.25
Pandas 관련 이것저것  (0) 2021.03.06
[파이썬] 간단한 그래프 그리기  (0) 2021.02.22
KERAS Convolution 필터 데이터 저장하기  (0) 2020.12.09
>>> from pymodbus.client.sync import ModbusTcpClient as ModbusClient
>>> import logging
>>> client = ModbusClient('localhost', port=502)
>>> client.connect()
True
>>> rr = client.read_coils(0, 1, unit=1)
>>> print(rr.bits)
[False, False, False, False, False, False, False, False]


>>> rr = client.read_holding_registers(1,18,unit=1)
>>> print(rr.registers)
[2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>>> rr = client.read_holding_registers(0,10,unit=1)
>>> print(rr.registers)
[1, 2, 0, 0, 0, 0, 0, 0, 0, 0]
>>> print(rr.registers)
[1, 2, 0, 0, 0, 0, 0, 0, 0, 0]
>>> rr = client.read_holding_registers(0,10,unit=1)
>>> print(rr.registers)
[1, 2, 3, 0, 0, 0, 0, 0, 0, 0]


>>> rq = client.write_register(1,10,unit=1)
>>> rq = client.write_register(2,10,unit=1)
>>> client.close()

 

 

 

 

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

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

 

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

 

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

 

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()

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

 

케라스 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%의 비율로 나누기

 

 

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() 

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

 

 

파이썬이 익숙하지 못해서 나중에 복붙이라도 할려고...

 


import numpy as np
import cv2

import matplotlib.pyplot as plt

# Read image
im = cv2.imread( 'e:/...Path..../image.bmp', cv2.IMREAD_GRAYSCALE )

print(im.shape)

plt.imshow(im)

im = im.reshape(-1)
print(im.shape)

 

#또 다른 방법

from PIL import Image 
import numpy 
im = Image.open('저장경로').convert('L') 
data = numpy.asarray(im) 
print(data.shape)

 

#여러개 파일 일괄 변환

import os
import cv2
import numpy as np

path_dir = '경로'

file_list = os.listdir(path_dir)

#일부 파일만 하고 싶을 때
#file_count = len(file_list)
file_count = 10
image_size = 35344

images_arr = np.zeros((file_count, image_size))

#모든 파일을 변환하려면 이렇게 해도 됨
#for filename in file_list:
#    im =  cv2.imread( os.path.join(path_dir,filename), cv2.IMREAD_GRAYSCALE )

for i in range(file_count):
    im =  cv2.imread( os.path.join(path_dir,file_list[i]), cv2.IMREAD_GRAYSCALE )
    im = im.reshape(-1)
    im = im[np.newaxis]
    #print(file_list[i])
    print(im[0])
    images_arr[i] = im

#print(len(images_arr[file_list]))
print(images_arr[0:5])
print(images_arr.shape)

'파이썬' 카테고리의 다른 글

텍스트 파일2개로 나누기  (0) 2020.09.11
이미지 파일 하나씩 조회하기  (0) 2020.06.30
수치미분  (0) 2019.10.05
Matplotlib scatter/line graph  (0) 2019.09.29
Numpy 이것저것  (0) 2019.09.29

+ Recent posts