'여행과 일상 > 일상' 카테고리의 다른 글

식스레시피 마라마라 떡볶이  (0) 2019.10.03

동영상 서비스가 종료되어 해당 콘텐츠를 재생할 수 없습니다.

 

식스레시피 마라마라떡볶이!!

 

마라와 떡볶이를 좋아하는 사람이라면 무조건 맛있는 맛!

 

우리는 기본 패키지에 제공된 우삼겹뿐만아니라 업진살까지 구워서 곁들여 먹었따 헤헤

 

조리법도 완전 간단하고! 마라 단계도 원하는대로 조절할 수 있어서 좋았다.

 

마라와 떡볶이를 좋아한다면 적극추천합니다! :)

 

'여행과 일상 > 일상' 카테고리의 다른 글

분당 서현 제주 은희네 해장국  (0) 2020.09.24

3. 동명이인 찾기

n명의 이름이 들어있는 리스트에서 여러 사람의 이름 중 같은 이름이 있는지 확인하고, 있다면 같은 이름들을 새로 만든 결과 집합에 넣어 돌려준다.

출력은 '집합(set)'이 나와야 함.

집합의 특성

In [1]:
s = set()
s.add(1)
s.add(2)
s.add(2) ##이미 2가 집합s에 들어가있어서 중복으로 들어가지 않는다
s
Out[1]:
{1, 2}
In [2]:
len(s) ## 집합s에는 자료가 두 개 들어있음
Out[2]:
2
In [3]:
{1,2} == {2,1} ##집합에서 자료의 순서는 무관해 두 집합은 같은 집합
Out[3]:
True

<동명이인을 찾는 알고리즘>

In [4]:
def find_same_name(a) :
    n = len(a)
    result = set() ##결과가 나올 빈 집합
    for i in range(0, n-1) : 
        for j in range(i + 1, n) :
            if a[i] == a[j] :
                result.add(a[i])
    return result

name = ["Zeun", "Dduk", "Zal", "Buk", "Zeun", "Zal"]
print(find_same_name(name))
{'Zeun', 'Zal'}
In [5]:
name2 = ["Zeun", "Dduk", "Zal", "Buk", "Dduk", "Dduk"]
print(find_same_name(name2))
{'Dduk'}

<n명 중 두 명을 뽑아 짝을 짓는다고 할 때 짝을 지을 수 있는 모든 조합을 출력>

In [6]:
def find_couple(a) :
    n = len(a)
    result = set()
    for i in range(0, n-1) :
        for j in range(i + 1, n) :
            if a[i] != a[j] :
                result.add(a[i]+'-'+a[j])
    return result

name = ["Zeun", "Dduk", "Zal", "Buk", "Zeun", "Zal"]
print(find_couple(name))
{'Zeun-Zal', 'Zal-Zeun', 'Dduk-Zeun', 'Zal-Buk', 'Dduk-Zal', 'Buk-Zeun', 'Dduk-Buk', 'Zeun-Buk', 'Buk-Zal', 'Zeun-Dduk'}

name에 중복된 이름이 포함되어있어, 위 알고리즘을 사용했을 때, 'Zeun-Zal', 'Zal-Zeun'이 사실 같은건데 다르게 출력됨.

In [7]:
name2 = ["Zeun", "Dduk", "Zal"] ##이름에 중복이 없으면 문제 없음
print(find_couple(name2)) 
{'Zeun-Zal', 'Dduk-Zal', 'Zeun-Dduk'}
In [8]:
name = ["Zeun", "Dduk", "Zal", "Buk", "Zeun", "Zal"]
distinct_name = list(set(name))

##이에 name을 집합(set)으로 바꿔주면 중복이 제거되고,
## 다시 리스트로 변환한 뒤 앞에서 만든 함수에 넣어줌

print(find_couple(distinct_name))
{'Zeun-Zal', 'Dduk-Zeun', 'Dduk-Zal', 'Buk-Zeun', 'Buk-Dduk', 'Buk-Zal'}

name에 중복된 이름이 있는 경우에 대해 만들고 싶어서 if문을 넣었는데, 결국 중복이 없는 리스트를 넣게 되므로 if문을 제외해 더 알고리즘을 간단하게 만든다.

In [9]:
def find_couple2(a) :
    n = len(a)
    for i in range(0, n-1) :
        for j in range(i + 1, n) :
            print(a[i]+'-'+a[j])

find_couple2(distinct_name)
Buk-Dduk
Buk-Zeun
Buk-Zal
Dduk-Zeun
Dduk-Zal
Zeun-Zal
2. 최댓값 찾기

2. 최댓값 찾기

리스트(list) 예제

In [1]:
a = [5, 7, 9] ## 리스트를 만들어 a에 저장
a
Out[1]:
[5, 7, 9]
In [2]:
a[0] ##파이썬에서는 첫번째 위치를 1이 아니고 0에서부터 센다.
Out[2]:
5
In [3]:
a[1] ##그러므로 1은 두번째 값인 7이 출력됨
Out[3]:
7
In [4]:
a[-1] ## -1은 리스트의 끝에서 첫번째 값. 즉 마지막 값을 의미 a[-1] = a[2] = a[자료길이-1]
Out[4]:
9
In [5]:
len(a) ## 리스트의 길이(자료의 개수)
Out[5]:
3
In [6]:
a.append(4) ##4를 리스트의 맨 뒤에 추가
a
Out[6]:
[5, 7, 9, 4]
In [7]:
a.insert(0,5) ## 0번 위치(맨 앞)에 5를 추가
a
Out[7]:
[5, 5, 7, 9, 4]
  1. 리스트에서 최댓값 구하기
In [8]:
#입력 : 숫자가 n개 들어있는 리스트
#출력 : 숫자 n개 중 최댓값

def find_max(a) : 
    n = len(a) #입력크기 n
    max_v = a[0] #리스트의 첫번째 값을 최댓값으로 기억
    for i in range(1,n) :
        if a[i] > max_v :
            max_v = a[i]
    return max_v

v = [25, 54, 87, 62, 48, 50, 685, 78, 8, 9 ,5]

print(find_max(v))
685
  1. 리스트에서 최대값의 위치 찾기
In [9]:
def find_max_idx(a) :
    n = len(a)
    max_idx = 0
    for i in range(1,n) :
        if a[i] > a[max_idx]:
            max_idx = i
    return max_idx

v = [25, 54, 87, 62, 48, 50, 685, 78, 8, 9 ,5]

print(find_max_idx(v))
6
  1. 리스트에서 최솟값 구하기
In [10]:
def find_min(a) : 
    n = len(a) #입력크기 n
    min_v = a[0] #리스트의 첫번째 값을 최솟값으로 기억
    for i in range(1,n) :
        if a[i] < min_v :
            min_v = a[i]
    return min_v

v = [25, 54, 87, 62, 48, 50, 685, 78, 8, 9 ,5]

print(find_min(v))
5
  1. 리스트에서 최솟값의 위치 찾기
In [11]:
def find_min_idx(a) :
    n = len(a)
    min_idx = 0
    for i in range(1,n) :
        if a[i] < a[min_idx]:
            min_idx = i
    return min_idx

v = [25, 54, 87, 62, 48, 50, 685, 78, 8, 9 ,5]

print(find_min_idx(v))
10
1. 연속한 숫자 합 구하기

1부터 n까지 합 구하기

  1. 1부터 n까지 숫자를 더해보자.
In [1]:
def sum_n(n) :
    s = 0
    for i in range(1, n+1) :
        s = s + i
    return s

print(sum_n(10))
print(sum_n(100))
55
5050
  1. 가우스의 공식으로 1부터 n까지 합을 구해보자.
In [2]:
def sum_n2(n) :
    return n * (n + 1) // 2

print(sum_n2(10))
print(sum_n2(100))
55
5050

첫번째 방법은 덧셈 n번 해야하며, 두번째 알고리즘은 덧셈, 곱셈, 나눗셈을 각 한번씩만 하면 됨 이에 두번째 방법이 더 효율적

어떤 알고리즘이 문제를 풀기 위해 해야 하는 계산이 얼마나 복잡한지 나타내는 정도를 계산 복잡도(complexity)라고 한다.

이를 표현하는 방법으로 대문자 O 표기법을 많이 사용함(빅오 라고도 부름)

첫번째 알고리즘은 n번의 덧셈을 해야 하기 때문에 O(n)라고 표현한다. n과 정비례하면 모두 O(n)이라고 표현.

두번째 알고리즘은 사칙연산을 세번 하며, 이 때는 O(1)으로 표현한다. 필요한 계산 횟수가 입력크기 n과 무관하면 모두 O(1)로 표현.

알고리즘을 만들 때는 O(n)이 아닌, O(1)로 만드는 연습을 해야한다.

  1. 1부터 n까지 연속한 숫자의 제곱의 합을 for문으로 만들어보자.
In [3]:
def sum_n3(n) :
    s = 0
    for i in range(1, n+1) :
        s = s + i**2
    return s

print(sum_n3(10))
print(sum_n3(100))
385
338350
  1. 1부터 n까지 연속한 숫자의 제곱을 구하는 공식을 이용해보자.
In [4]:
def sum_n4(n) :
    return n*(n + 1)*(2*n + 1) // 6

print(sum_n4(10))
print(sum_n4(100))
385
338350

sum_n3의 경우 계산 복잡도가 O(n)이며, sum_n4의 경우 O(1)으로 sum_n4가 효율적이다.

'프로그래밍 > Python' 카테고리의 다른 글

[모두의 알고리즘] 3. 동명이인 찾기  (0) 2019.10.03
[모두의 알고리즘] 2. 최댓값 찾기  (0) 2019.10.03
[OpenCV] Color K-Means  (0) 2019.10.02
[OpenCV] 이미지 합치기  (0) 2019.10.02
[OpenCV] 이미지 불러오기  (0) 2019.10.02
K-Means
In [1]:
import numpy as np
import cv2
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
In [2]:
img1 = cv2.imread("../img/inchan.png", cv2.IMREAD_UNCHANGED)
img2 = cv2.imread("../img/mado.jpg", cv2.IMREAD_UNCHANGED) #이미지파일을 alpha channel까지 포함하여 로드
In [3]:
print(img1.shape)
print(img2.shape)
(661, 1540, 4)
(427, 580, 3)
In [4]:
# 채널을 BGR -> RGB로 변경
img1_1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB)
img2_1 = cv2.cvtColor(img2, cv2.COLOR_BGR2RGB)
In [5]:
img1_2 = img1_1.reshape((img1_1.shape[0] * img1_1.shape[1], 3)) # height, width 통합
img2_2 = img2_1.reshape((img2_1.shape[0] * img2_1.shape[1], 3)) # height, width 통합

print(img1_2.shape)
print(img2_2.shape)
(1017940, 3)
(247660, 3)
In [6]:
k = 5 
clt = KMeans(n_clusters = k)
clt.fit(img2_2)
Out[6]:
KMeans(algorithm='auto', copy_x=True, init='k-means++', max_iter=300,
    n_clusters=5, n_init=10, n_jobs=1, precompute_distances='auto',
    random_state=None, tol=0.0001, verbose=0)
In [7]:
for center in clt.cluster_centers_:
    print(center)
[80.53909992 25.56062977 38.58291839]
[209.69067153 194.42864266 209.96754527]
[187.22068381 121.54902515 134.21712348]
[240.73005074 229.11786865 241.83149271]
[143.86622928  56.529928    66.2291569 ]
In [8]:
def centroid_histogram(clt):
    # grab the number of different clusters and create a histogram
    # based on the number of pixels assigned to each cluster
    numLabels = np.arange(0, len(np.unique(clt.labels_)) + 1)
    (hist, _) = np.histogram(clt.labels_, bins=numLabels)

    # normalize the histogram, such that it sums to one
    hist = hist.astype("float")
    hist /= hist.sum()

    # return the histogram
    return hist


hist = centroid_histogram(clt)
print(hist)
[0.08522975 0.35633126 0.07139627 0.39218283 0.09485989]
In [9]:
def plot_colors(hist, centroids):
    # initialize the bar chart representing the relative frequency
    # of each of the colors
    bar = np.zeros((50, 300, 3), dtype="uint8")
    startX = 0

    # loop over the percentage of each cluster and the color of
    # each cluster
    for (percent, color) in zip(hist, centroids):
        # plot the relative percentage of each cluster
        endX = startX + (percent * 300)
        cv2.rectangle(bar, (int(startX), 0), (int(endX), 50),
                      color.astype("uint8").tolist(), -1)
        startX = endX

    # return the bar chart
    return bar

bar = plot_colors(hist, clt.cluster_centers_)


# show our color bart
plt.figure()
plt.axis("off")
plt.imshow(bar)
plt.show()

#https://www.pyimagesearch.com/2014/05/26/opencv-python-k-means-color-clustering/
In [10]:
plt.imshow(img2_1) 
plt.show()
In [11]:
k = 5 
clt = KMeans(n_clusters = k)
clt.fit(img1_2)
Out[11]:
KMeans(algorithm='auto', copy_x=True, init='k-means++', max_iter=300,
    n_clusters=5, n_init=10, n_jobs=1, precompute_distances='auto',
    random_state=None, tol=0.0001, verbose=0)
In [12]:
for center in clt.cluster_centers_:
    print(center)
[34.39905783 12.87719814 37.72506877]
[219.45508718 180.41651953 209.98856489]
[139.95229495  90.18944664 136.50906154]
[60.44522255 23.57638168 89.22992637]
[148.916066    21.58758298  19.69360567]
In [13]:
def centroid_histogram(clt):
    # grab the number of different clusters and create a histogram
    # based on the number of pixels assigned to each cluster
    numLabels = np.arange(0, len(np.unique(clt.labels_)) + 1)
    (hist, _) = np.histogram(clt.labels_, bins=numLabels)

    # normalize the histogram, such that it sums to one
    hist = hist.astype("float")
    hist /= hist.sum()

    # return the histogram
    return hist


hist = centroid_histogram(clt)
print(hist)
[0.31071379 0.0711987  0.07722557 0.47530405 0.06555789]
In [14]:
def plot_colors(hist, centroids):
    # initialize the bar chart representing the relative frequency
    # of each of the colors
    bar = np.zeros((50, 300, 3), dtype="uint8")
    startX = 0

    # loop over the percentage of each cluster and the color of
    # each cluster
    for (percent, color) in zip(hist, centroids):
        # plot the relative percentage of each cluster
        endX = startX + (percent * 300)
        cv2.rectangle(bar, (int(startX), 0), (int(endX), 50),
                      color.astype("uint8").tolist(), -1)
        startX = endX

    # return the bar chart
    return bar

bar = plot_colors(hist, clt.cluster_centers_)


# show our color bart
plt.figure()
plt.axis("off")
plt.imshow(bar)
plt.show()

#https://www.pyimagesearch.com/2014/05/26/opencv-python-k-means-color-clustering/
In [15]:
plt.imshow(img1_1) 
plt.show()
Prac2
In [1]:
import cv2
import numpy as np
import matplotlib.pylab as plt
%matplotlib inline
In [2]:
rain = cv2.imread('../img/rain.png')
th = cv2.imread('../img/th.png')

## 단순히 더해주는 로직. 이에 화소가 고르지 못하고 중간중간 이상한 색을 띌 수 있음
## >> 255를 초과하는 영역
rain_th = rain + th

## 전체적으로 하얀 픽셀을 많이 가져감
rain_th2 = cv2.add(rain,th)

imgs = {'rain' : rain, 'th' : th, 
		'rain + th' : rain_th, 'cv2.add(rain,th)' : rain_th2}

for i, (k,v) in enumerate(imgs.items()):
	plt.subplot(2,2,i+1)
	plt.imshow(v[:,:,::-1])
	plt.title(k)
	plt.xticks([]); plt.yticks([])
plt.show()
In [3]:
img1 = cv2.imread('../img/0001.png')
img2 = cv2.imread('../img/0002.png')
img3 = cv2.imread('../img/0003.png')

## 레이어 겹쳐주는데는 문제없어보임..?
img4 = img1 + img2 + img3

imgs = {'img1' : img1, 'img2' : img2, 'img3' : img3,
		'img1+img2+img3' : img4}

for i, (k,v) in enumerate(imgs.items()):
	plt.subplot(2,3,i+1)
	plt.imshow(v[:,:,::-1])
	plt.xticks([]); plt.yticks([])
plt.show()
In [4]:
alpha = 0.5

## 수식사용
blended = rain * alpha + th *(1-alpha)
blended= blended.astype(np.uint8)
cv2.imshow('rain * alpha + th *(1-alpha)', blended)
plt.show()

cv2.waitKey(0)
cv2.destroyAllWindows()
In [5]:
##함수사용
dst = cv2.addWeighted(rain, alpha, th, (1-alpha),0)
cv2.imshow('cv2.addWeighted',dst)
plt.show()

cv2.waitKey(0)
cv2.destroyAllWindows()
Prac1
In [1]:
import numpy as np #numpy
import cv2 #opencv
import matplotlib.pyplot as plt ##matplot
In [2]:
print("hello")
print(np.__version__)
print(cv2.__version__)
hello
1.14.3
4.1.0
In [4]:
img_file = "../img/img2.png"
print("img_file : ", img_file)

img2_gray = cv2.imread(img_file, cv2.IMREAD_GRAYSCALE)
img2 = cv2.imread(img_file)
img2_orign = cv2.imread(img_file, cv2.IMREAD_UNCHANGED) #이미지파일을 alpha channel까지 포함하여 로드

print("img2.shape : " , img2.shape) ##이미지크기
print("img2.ndim : " , img2.ndim) ##차원(row,column,channel) ##channel이 색상(r,g,b라서 3)
print("img2.size : " ,img2.size)

## b,g,r = img2[:,:,0], img2[:,:,1], img2[:,:,2]
img_file :  ../img/img2.png
img2.shape :  (230, 200, 3)
img2.ndim :  3
img2.size :  138000
In [5]:
plt.imshow(img2_gray) #흑백으로 변환한 이미지
plt.show()
In [11]:
plt.imshow(img2) #원본이미지
plt.show()
In [14]:
plt.imshow(img2_orign) #원본이미지
plt.show()
In [13]:
## openCV는 이미지를 B,G,R 순으로 만들어지고, plt.show는 R,G,B순으로 해석
## 그래서 위 이미지들이 생각과 다르게 출력됨


b, g, r = cv2.split(img2)   # img파일을 b,g,r로 분리
img2_orign2 = cv2.merge([r,g,b]) # b, r을 바꿔서 Merge
plt.imshow(img2_orign2) #원본이미지
plt.show()
In [10]:
## RGB로 바꾸는 다른 방법

plt.imshow(img2[:,:,::-1]) #이미지 컬러 채널 변경해서 표시. 원본 이미지가 잘 출력됨
plt.xticks([]) #x좌표 눈금 제거
plt.yticks([]) #y좌표 눈금 제거
plt.show()
In [7]:
plt.subplot(1,3,1)
plt.imshow(img2)
plt.xticks([]) #x좌표 눈금 제거
plt.yticks([]) #y좌표 눈금 제거

plt.subplot(1,3,2)
plt.imshow(img2_gray)
plt.xticks([]) #x좌표 눈금 제거
plt.yticks([]) #y좌표 눈금 제거

plt.subplot(1,3,3)
plt.imshow(img2[:,:,::-1])
plt.xticks([]) #x좌표 눈금 제거
plt.yticks([]) #y좌표 눈금 제거
Out[7]:
([], <a list of 0 Text yticklabel objects>)

+ Recent posts