for i in range(1,101): #시작, 끝+1
    zipfile.ZipFile(f'F:\\3D\\{i}\\{i}_after.zip').extractall(f'F:\\3D\\{i}') # 폴더위치, 해제할 파일 
    zipfile.ZipFile(f'F:\\3D\\{i}\\{i}_before.zip').extractall(f'F:\\3D\\{i}')
    print(i)

 

'Python > 기능' 카테고리의 다른 글

이미지 용량 줄이기  (0) 2022.04.19
폴더에서 원하는 확장자 파일 삭제  (0) 2021.12.24
원하는 폴더들 띄우기  (0) 2021.12.24
OpenCV) 이미지 이동  (0) 2021.11.29
OpenCV) 이미지 resize  (0) 2021.11.29
img = cv2.imread('./test_1118.jpg')
num_rows,num_cols = img.shape[:2]
translation_matrix = np.float32([[1,0,23],[0,1,59]]) # 이동할 픽셀 거리, x방향으로 23 y방향으로 59만큼 이동된 것 
img_translation = cv2.warpAffine(img,translation_matrix,(num_cols,num_rows),cv2.INTER_LINEAR) # 열,행 순서로
cv2.imshow('Trans',img_translation)
cv2.imwrite('./test_1118_2.jpg', img_translation)
cv2.waitKey(0)
cv2.destroyAllWindows()

 

'Python > 기능' 카테고리의 다른 글

이미지 용량 줄이기  (0) 2022.04.19
폴더에서 원하는 확장자 파일 삭제  (0) 2021.12.24
원하는 폴더들 띄우기  (0) 2021.12.24
알집폴더 풀기  (0) 2021.12.24
OpenCV) 이미지 resize  (0) 2021.11.29
import cv2
import numpy as np

src = cv2.imread('./a.jpg', cv2.INTER_AREA) # 경로

dst = cv2.resize(src, dsize=(800, 800), interpolation=cv2.INTER_AREA) # 특정 크기로 줄이고 싶을 때 (w, h)
dst = cv2.resize(src, dsize=(0, 0), fx=1.6, fy=1.6, interpolation=cv2.INTER_LINEAR) # 비율로 줄이고 싶을 때 
cv2.imwrite('./b.jpg', dst) # 저장
cv2.imshow("dst", dst2)


dst2_copy = dst.copy()
dst2_crop = dst2_copy[8:808, 16:] # 필요없는 부분 crop 
print(dst2_crop.shape)
cv2.imshow("11", dst2_crop)
cv2.imwrite('./test.jpg', dst2_crop)
cv2.waitKey()
cv2.destroyAllWindows()

'Python > 기능' 카테고리의 다른 글

이미지 용량 줄이기  (0) 2022.04.19
폴더에서 원하는 확장자 파일 삭제  (0) 2021.12.24
원하는 폴더들 띄우기  (0) 2021.12.24
알집폴더 풀기  (0) 2021.12.24
OpenCV) 이미지 이동  (0) 2021.11.29

가장 근사한 방정식 구하기 

[다항회귀] 

 

- x, y좌표들을 지나는 가장 근사한 방정식 구하기 

- 구한 방정식에서 새로운 x를 넣었을 때 y값 추출 

import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression

# x,y좌표를 지나는 가장 근사한 방정식 구하기 

# x, y 좌표 리스트 
x = np.array([[100], [106], [111], [124], [151], [187], [226], [270], [315], [354], [390], [415], [428], [434], [439]])
y = np.array([[259], [301], [344], [386], [419], [445], [467], [474], [468], [445], [418], [384], [342], [300], [258]])

poly_features = PolynomialFeatures(degree=4, include_bias=True) # degree, 차수를 바꿔가면서 방정식 확인 
x_poly = poly_features.fit_transform(x)
# print(x_poly)

lin_reg = LinearRegression()
lin_reg.fit(x_poly, y)
lin_reg.intercept_ , lin_reg.coef_

# 위에서 구한 방정식에서 x좌표를 넣으면 y좌표를 예측해줌 
x_new = np.array([[102], [112], [124], [142], [165], [194], [229], [270], [310], [346], [376], [399], [417], [429], [439]])
x_new_poly = poly_features.transform(x_new)
y_new = lin_reg.predict(x_new_poly)
# print(y_new)


plt.plot(x, y, "b.")
plt.plot(x_new2, y_new, "r-", linewidth=2, label="Predictions")
plt.xlabel("$x$", fontsize=16, labelpad=5)
plt.ylabel("$y$", rotation=0, fontsize=16, labelpad=15)
plt.title('KimTaeHee_LandmarkPoint(1~15)')
plt.legend(loc="upper left", fontsize=10)
plt.savefig('./result2.jpg', bbox_inches='tight', pad_inches=0)
plt.show()

 

 

 

- x, y좌표들을 지나는 가장 근사한 방정식 구하기

- 구한 방정식에서 새로운 x를 넣었을 때 y값 추출 

from sklearn import linear_model
import matplotlib.pyplot as plt

# [x, y] 
Data = [[127, 388], [138, 462], [148, 535], [172, 606], [218, 662], [279, 707], [347, 744], [422, 756],
         [498, 746], [566, 708], [625, 660], [669, 602], [693, 530], [703, 456], [713,383]]


x = [Data[0][0], Data[1][0], Data[2][0], Data[3][0], Data[4][0], Data[5][0], Data[6][0], Data[7][0], Data[8][0], Data[9][0], Data[10][0], Data[11][0], Data[12][0], Data[13][0], Data[14][0]]
y = [Data[0][1], Data[1][1], Data[2][1], Data[3][1], Data[4][1], Data[5][1], Data[6][1], Data[7][1], Data[8][1], Data[9][1], Data[10][1], Data[11][1], Data[12][1], Data[13][1], Data[14][1]]


X = [[x[k]**n for n in range(1, 3)] for k in range(len(Data))]

reg = linear_model.LinearRegression()
reg.fit(X, y)
# print(reg.intercept_)
# print(reg.coef_)

#accuracy 값 
print(reg.score(X,y))


xp = [k for k in range(800)]
Xp = [[xp[k]**n for n in range(1, 3)] for k in range(800)]
# xp = [75, 79, 86, 92, 107, 137, 177, 221, 270, 319, 363, 402, 430, 446, 452, 459, 462]
# Xp = [[xp[k]**n for n in range(1, 7)] for k in range(17)]
yp = reg.predict(Xp)
# print(yp)
# print('\n')


plt.xlim(50, 800)
plt.ylim(100, 800)
plt.plot(x, y, "x")
plt.plot(xp, yp)
plt.savefig('./test_shape.jpg', bbox_inches='tight', pad_inches=0)
plt.show()

 

 

- x, y좌표들을 지나는 가장 근사한 방정식 구하기

- 구한 방정식에서 새로운 x를 넣었을 때 y값 추출 

- +) 구한 방정식에서 새로운 y를 넣었을 때 x값 추출 

import numpy as np
import matplotlib.pyplot as plt
from sympy import Symbol, solve
from sympy import *

# x,y좌표 리스트 
x = [69, 78, 89, 105, 124, 148, 176, 206, 236, 264, 289, 309, 324, 335, 344]
y = [166, 204, 239, 274, 306, 335, 354, 361, 355, 336, 309, 276, 241, 203, 164]


# x,y 좌표를 지나는 가장 근사한 방정식 구하기 
fit6 = np.polyfit(x, y, 6) # 6차 
#print(fit6)

x1 = [100, 106, 111, 124, 151, 187, 226, 270, 315, 354, 390, 415, 428, 434, 439]
y1 = []


# 방정식에서 x1값을 넣었을 때의 y1값 
for i in x1:
    y_predit = fit6[0]*(i**6) + fit6[1]*(i**5) + fit6[2]*(i**4) + fit6[3]*(i**3) + fit6[4]*(i**2) + fit6[5]*(i**1) + fit6[6]
    y1.append(y_predit)

# print(y1)

# 방정식에서 yy값을 넣었을 때의 x0값 구하기 / 259자리에 y값 넣어주면 됨  
x0 = symbols('x0')
eqn = Eq(fit6[0] * (x0 ** 6) + fit6[1] * (x0 ** 5) + fit6[2] * (x0 ** 4) + fit6[3] * (x0 ** 3) + fit6[4] * (x0 ** 2) + fit6[5] * (x0 ** 1) + fit6[6] - 259, 0)
yy = solve(eqn, x0)
print(yy)

fit6_model = np.poly1d(fit6)
# print(fit6_model)
x_s = np.arange(50,450)

plt.scatter(x,y, c='blue', s=20)
plt.plot(x_s, fit6_model(x_s), color='orange')
plt.ylim(150,500)
plt.xlabel("$x$", fontsize=16, labelpad=5)
plt.ylabel("$y$", rotation=0, fontsize=16, labelpad=15)
plt.savefig('./numpy.jpg', bbox_inches='tight', pad_inches=0)
plt.show()

'Python' 카테고리의 다른 글

Blending  (0) 2021.11.26
Seaborn, Matplotlib  (0) 2020.10.04
마크다운 요약  (0) 2020.09.29
Python_우리나라 아기이름 데이터 분석  (1) 2020.09.15
Python_데이터분석2  (0) 2020.09.15
import cv2
import matplotlib.pyplot as plt

a = 0.0
count = 0

while(a <= 1.0):

    img1 = cv.imread('ref.jpg')
    img2 = cv.imread('result2.jpg')

    # img1 사진은 점점 투명해지고 img2 사진은 점점 불투명해짐
    b = 1.0 - a
    dst = cv.addWeighted(img1, a, img2, b, 0)
    cv.imshow('dst', dst)
    cv.waitKey(0)
    cv2.imwrite(f'blending{count}.jpg', dst)
    count += 1
    a = a + 0.1

cv.destroyAllWindows()

'Python' 카테고리의 다른 글

파이썬/ sklearn/가장 근사한 방정식 구하기/다항회귀  (0) 2021.11.26
Seaborn, Matplotlib  (0) 2020.10.04
마크다운 요약  (0) 2020.09.29
Python_우리나라 아기이름 데이터 분석  (1) 2020.09.15
Python_데이터분석2  (0) 2020.09.15
Untitled2

ndarray.flatten(order='C)

: 텐서를 벡터로 만듦

In [1]:
import numpy as np
In [2]:
A = np.arange(4)
B = A.reshape((2, 2))
C = B.flatten()

print(A, '\n')
print(B, '\n')
print(C, '\n')
[0 1 2 3] 

[[0 1]
 [2 3]] 

[0 1 2 3] 

ndarray.ravel([])

:텐서를 벡터로 만듦

In [7]:
A = np.arange(4)
B = A.reshape((2, 2))
C = B.ravel()

print(A, '\n')
print(B, '\n')
print(C, '\n')
[0 1 2 3] 

[[0 1]
 [2 3]] 

[0 1 2 3] 

flatten과 ravel의 차이점을 설명하기 전에 copy와 view 알아보기

copy : 메모리 용량 많이 차지 but b를 수정해도 a(원본) 영향 없음

view : 메모리 적게 사용가능 but b를 수정하면 a(원본)수정됨

In [8]:
a = np.arange(5)
b = a.view()

b[0] = 10 

print(a)
print(b)
[10  1  2  3  4]
[10  1  2  3  4]

a와 b는 같은 메모리 address 그래서 b를 수정하면 a도 수정됨

   

In [10]:
a = np.arange(5)
b = a[:3]

b[0] = 10 

print(a)
print(b)
[10  1  2  3  4]
[10  1  2]

넘파이에서 슬라이싱은 view를 만드는 것

슬라이싱을 통해 만들어진 값(b)을 수정하면 원본(a)에도 영향을 미침

   

In [12]:
a = np.arange(5)
b = a.copy()

b[0] = 10 

print(a)
print(b)
[0 1 2 3 4]
[10  1  2  3  4]

a, b는 다른 메모리, 서로 영향없음

 
 
 
 

base

In [13]:
a = np.arange(5)
b = a.copy()
c = a.view()
d = a[:3]

print(b.base is a)
print(c.base is a)
print(d.base is a)
False
True
True

view를 통해 만들어진 객체들의 base는 메모리 address를 제공해준 ndarray다

ex) b,c의 base는 a

 
 
 
 

In [17]:
a = np.arange(4)
b = np.reshape(a, (2, 2))
b[0, 0] = 10

print(b.base is a, '\n')
print(a, '\n')
print(b)
True 

[10  1  2  3] 

[[10  1]
 [ 2  3]]
In [18]:
a = np.arange(4)
b = np.resize(a, (2, 2))
b[0, 0] = 10

print(b.base is a, '\n')
print(a, '\n')
print(b)
False 

[0 1 2 3] 

[[10  1]
 [ 2  3]]

reshape으로 만들었을 때는 원소 바꿀 때 조심

view를 통해서 만드므로 원본 영향 줌

 

resize는 copy를 통해서 만듦, 원본 영향없음

In [21]:
a = np.arange(4)
b = np.reshape(a, (2,2)).copy() # 이렇게 쓰면 원본 영향없음

b[0,0] = 10

print(b.base is a, '\n')
print(a, '\n')
print(b)
False 

[0 1 2 3] 

[[10  1]
 [ 2  3]]

 
 
 
 

In [26]:
a = np.random.randint(0, 10, (3,3))
b = a.ravel()
b[0] = 10 

print(b.base is a, '\n')
print(a, '\n')
print(b)
True 

[[10  1  2]
 [ 9  2  2]
 [ 1  9  6]] 

[10  1  2  9  2  2  1  9  6]
In [27]:
a = np.random.randint(0, 10, (3,3))
b = a.flatten()
b[0] = 10 

print(b.base is a, '\n')
print(a, '\n')
print(b)
False 

[[1 4 9]
 [0 2 7]
 [8 8 2]] 

[10  4  9  0  2  7  8  8  2]

ravel: view를 통해서 만듦, 메모리 효과적으로 사용

: flatten시킨 다음에 원소 수정하겠다

 

flatten: copy를 통해서 만듦, 원본 영향 없음

: flatten시킨 다음에 원소 수정 안 하겠다

Untitled2

numpy.reshape(a, newshape, order='C)

In [2]:
import numpy as np

reshape: 원하는 shape으로 바꿔줌

In [6]:
a = np.arange(10)
b = np.reshape(a, (2, 5))
c = a.reshape((2, 5))

print('a:\n', a)
print('b:\n', b)
print('c:\n', c)
a:
 [0 1 2 3 4 5 6 7 8 9]
b:
 [[0 1 2 3 4]
 [5 6 7 8 9]]
c:
 [[0 1 2 3 4]
 [5 6 7 8 9]]

하나를 지정하지 않고 -1을 쓰면 자동으로 shape이 됨

계산이 귀찮거나 row나 column 강조하고싶을 때 사용해도 좋음

In [11]:
a = np.arange(10)

b = a.reshape((2, -1)) # row가 강조되는 느낌 
c = a.reshape((5, -1))

print(b.shape)
print(c.shape)
(2, 5)
(5, 2)

numpy.resize(a, new_shape)

원소의 개수를 바꿔줄 때 유용

아래의 코드는 reshape과 결과가 같음

In [12]:
a = np.arange(10)

b = np.resize(a, (2, 5))

print('a:\n', a)
print('b:\n', b)
a:
 [0 1 2 3 4 5 6 7 8 9]
b:
 [[0 1 2 3 4]
 [5 6 7 8 9]]

but reshape은 원소의 개수가 다르면 오류가 나지만 resize는 자동으로 맞춰줌

In [14]:
a = np.arange(5)

b = np.reshape(a, (10,))
print('b:\n', b)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-14-fcc2b57f1b7d> in <module>
      1 a = np.arange(5)
      2 
----> 3 b = np.reshape(a, (10,))
      4 print('b:\n', b)

<__array_function__ internals> in reshape(*args, **kwargs)

~\anaconda3\lib\site-packages\numpy\core\fromnumeric.py in reshape(a, newshape, order)
    299            [5, 6]])
    300     """
--> 301     return _wrapfunc(a, 'reshape', newshape, order=order)
    302 
    303 

~\anaconda3\lib\site-packages\numpy\core\fromnumeric.py in _wrapfunc(obj, method, *args, **kwds)
     59 
     60     try:
---> 61         return bound(*args, **kwds)
     62     except TypeError:
     63         # A TypeError occurs if the object does have such a method in its

ValueError: cannot reshape array of size 5 into shape (10,)
In [16]:
a = np.arange(5)

b = np.resize(a, (10,))
print('b:\n', b)
# 앞에서부터 반복해서 만듦 
b:
 [0 1 2 3 4 0 1 2 3 4]

size가 늘어나도 오류가 안나므로 조심해야 함

 
 

resize는 in-place (return값이 없고 바로 바뀜)

In [18]:
a = np.arange(4)

b = a.resize((2, 2))

print('a: \n', a)
print('b:\n', b)
a: 
 [[0 1]
 [2 3]]
b:
 None

그래서 아래와 같이 사용하는게 좋음

In [21]:
a = np.arange(5)

a.resize((2,2))
print(a)
[[0 1]
 [2 3]]

reshape은 오류남

In [24]:
a = np.arange(5)

a.reshape((2,2))
print(a)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-24-f82f97014a0d> in <module>
      1 a = np.arange(5)
      2 
----> 3 a.reshape((2,2))
      4 print(a)

ValueError: cannot reshape array of size 5 into shape (2,2)

np.ndim -> 차원 

np.shape -> row, column 확인 

np.size -> 개수 

 

.dtype -> 데이터 타입확인 ex) int64, float64 

         -> 데이터 타입 명시적으로 설정 가능 

int8_np = np.array([1, 2, 3], dtype=np.int8) 

: 데이터 타입 int8이 됨 

 

.itemsize ->넘파이 array에 많은 값이 있을 떄 값들이 각각 몇 바이트인지 숫자로 표현, 원소1개 용량 표현

 

.nbytes -> 넘파이 array의 원소들이 차지하는 용량을 담고 있는 데이터

          -> size*itemsize 와 같음  

+ Recent posts