'여행과 일상 > 일상' 카테고리의 다른 글
식스레시피 마라마라 떡볶이 (0) | 2019.10.03 |
---|
식스레시피 마라마라 떡볶이 (0) | 2019.10.03 |
---|
식스레시피 마라마라떡볶이!!
마라와 떡볶이를 좋아하는 사람이라면 무조건 맛있는 맛!
우리는 기본 패키지에 제공된 우삼겹뿐만아니라 업진살까지 구워서 곁들여 먹었따 헤헤
조리법도 완전 간단하고! 마라 단계도 원하는대로 조절할 수 있어서 좋았다.
마라와 떡볶이를 좋아한다면 적극추천합니다! :)
분당 서현 제주 은희네 해장국 (0) | 2020.09.24 |
---|
n명의 이름이 들어있는 리스트에서 여러 사람의 이름 중 같은 이름이 있는지 확인하고, 있다면 같은 이름들을 새로 만든 결과 집합에 넣어 돌려준다.
출력은 '집합(set)'이 나와야 함.
집합의 특성
s = set()
s.add(1)
s.add(2)
s.add(2) ##이미 2가 집합s에 들어가있어서 중복으로 들어가지 않는다
s
len(s) ## 집합s에는 자료가 두 개 들어있음
{1,2} == {2,1} ##집합에서 자료의 순서는 무관해 두 집합은 같은 집합
<동명이인을 찾는 알고리즘>
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))
name2 = ["Zeun", "Dduk", "Zal", "Buk", "Dduk", "Dduk"]
print(find_same_name(name2))
<n명 중 두 명을 뽑아 짝을 짓는다고 할 때 짝을 지을 수 있는 모든 조합을 출력>
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))
name에 중복된 이름이 포함되어있어, 위 알고리즘을 사용했을 때, 'Zeun-Zal', 'Zal-Zeun'이 사실 같은건데 다르게 출력됨.
name2 = ["Zeun", "Dduk", "Zal"] ##이름에 중복이 없으면 문제 없음
print(find_couple(name2))
name = ["Zeun", "Dduk", "Zal", "Buk", "Zeun", "Zal"]
distinct_name = list(set(name))
##이에 name을 집합(set)으로 바꿔주면 중복이 제거되고,
## 다시 리스트로 변환한 뒤 앞에서 만든 함수에 넣어줌
print(find_couple(distinct_name))
name에 중복된 이름이 있는 경우에 대해 만들고 싶어서 if문을 넣었는데, 결국 중복이 없는 리스트를 넣게 되므로 if문을 제외해 더 알고리즘을 간단하게 만든다.
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)
[모두의 알고리즘] 2. 최댓값 찾기 (0) | 2019.10.03 |
---|---|
[모두의 알고리즘] 1. 연속한 숫자 합 구하기 (0) | 2019.10.03 |
[OpenCV] Color K-Means (0) | 2019.10.02 |
[OpenCV] 이미지 합치기 (0) | 2019.10.02 |
[OpenCV] 이미지 불러오기 (0) | 2019.10.02 |
리스트(list) 예제
a = [5, 7, 9] ## 리스트를 만들어 a에 저장
a
a[0] ##파이썬에서는 첫번째 위치를 1이 아니고 0에서부터 센다.
a[1] ##그러므로 1은 두번째 값인 7이 출력됨
a[-1] ## -1은 리스트의 끝에서 첫번째 값. 즉 마지막 값을 의미 a[-1] = a[2] = a[자료길이-1]
len(a) ## 리스트의 길이(자료의 개수)
a.append(4) ##4를 리스트의 맨 뒤에 추가
a
a.insert(0,5) ## 0번 위치(맨 앞)에 5를 추가
a
#입력 : 숫자가 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))
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))
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))
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))
[모두의 알고리즘] 3. 동명이인 찾기 (0) | 2019.10.03 |
---|---|
[모두의 알고리즘] 1. 연속한 숫자 합 구하기 (0) | 2019.10.03 |
[OpenCV] Color K-Means (0) | 2019.10.02 |
[OpenCV] 이미지 합치기 (0) | 2019.10.02 |
[OpenCV] 이미지 불러오기 (0) | 2019.10.02 |
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))
def sum_n2(n) :
return n * (n + 1) // 2
print(sum_n2(10))
print(sum_n2(100))
첫번째 방법은 덧셈 n번 해야하며, 두번째 알고리즘은 덧셈, 곱셈, 나눗셈을 각 한번씩만 하면 됨 이에 두번째 방법이 더 효율적
어떤 알고리즘이 문제를 풀기 위해 해야 하는 계산이 얼마나 복잡한지 나타내는 정도를 계산 복잡도(complexity)라고 한다.
이를 표현하는 방법으로 대문자 O 표기법을 많이 사용함(빅오 라고도 부름)
첫번째 알고리즘은 n번의 덧셈을 해야 하기 때문에 O(n)라고 표현한다. n과 정비례하면 모두 O(n)이라고 표현.
두번째 알고리즘은 사칙연산을 세번 하며, 이 때는 O(1)으로 표현한다. 필요한 계산 횟수가 입력크기 n과 무관하면 모두 O(1)로 표현.
알고리즘을 만들 때는 O(n)이 아닌, O(1)로 만드는 연습을 해야한다.
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))
def sum_n4(n) :
return n*(n + 1)*(2*n + 1) // 6
print(sum_n4(10))
print(sum_n4(100))
sum_n3의 경우 계산 복잡도가 O(n)이며, sum_n4의 경우 O(1)으로 sum_n4가 효율적이다.
[모두의 알고리즘] 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 |
import numpy as np
import cv2
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
img1 = cv2.imread("../img/inchan.png", cv2.IMREAD_UNCHANGED)
img2 = cv2.imread("../img/mado.jpg", cv2.IMREAD_UNCHANGED) #이미지파일을 alpha channel까지 포함하여 로드
print(img1.shape)
print(img2.shape)
# 채널을 BGR -> RGB로 변경
img1_1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB)
img2_1 = cv2.cvtColor(img2, cv2.COLOR_BGR2RGB)
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)
k = 5
clt = KMeans(n_clusters = k)
clt.fit(img2_2)
for center in clt.cluster_centers_:
print(center)
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)
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/
plt.imshow(img2_1)
plt.show()
k = 5
clt = KMeans(n_clusters = k)
clt.fit(img1_2)
for center in clt.cluster_centers_:
print(center)
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)
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/
plt.imshow(img1_1)
plt.show()
[모두의 알고리즘] 3. 동명이인 찾기 (0) | 2019.10.03 |
---|---|
[모두의 알고리즘] 2. 최댓값 찾기 (0) | 2019.10.03 |
[모두의 알고리즘] 1. 연속한 숫자 합 구하기 (0) | 2019.10.03 |
[OpenCV] 이미지 합치기 (0) | 2019.10.02 |
[OpenCV] 이미지 불러오기 (0) | 2019.10.02 |
import cv2
import numpy as np
import matplotlib.pylab as plt
%matplotlib inline
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()
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()
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()
##함수사용
dst = cv2.addWeighted(rain, alpha, th, (1-alpha),0)
cv2.imshow('cv2.addWeighted',dst)
plt.show()
cv2.waitKey(0)
cv2.destroyAllWindows()
[모두의 알고리즘] 3. 동명이인 찾기 (0) | 2019.10.03 |
---|---|
[모두의 알고리즘] 2. 최댓값 찾기 (0) | 2019.10.03 |
[모두의 알고리즘] 1. 연속한 숫자 합 구하기 (0) | 2019.10.03 |
[OpenCV] Color K-Means (0) | 2019.10.02 |
[OpenCV] 이미지 불러오기 (0) | 2019.10.02 |
import numpy as np #numpy
import cv2 #opencv
import matplotlib.pyplot as plt ##matplot
print("hello")
print(np.__version__)
print(cv2.__version__)
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]
plt.imshow(img2_gray) #흑백으로 변환한 이미지
plt.show()
plt.imshow(img2) #원본이미지
plt.show()
plt.imshow(img2_orign) #원본이미지
plt.show()
## 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()
## RGB로 바꾸는 다른 방법
plt.imshow(img2[:,:,::-1]) #이미지 컬러 채널 변경해서 표시. 원본 이미지가 잘 출력됨
plt.xticks([]) #x좌표 눈금 제거
plt.yticks([]) #y좌표 눈금 제거
plt.show()
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좌표 눈금 제거
[모두의 알고리즘] 3. 동명이인 찾기 (0) | 2019.10.03 |
---|---|
[모두의 알고리즘] 2. 최댓값 찾기 (0) | 2019.10.03 |
[모두의 알고리즘] 1. 연속한 숫자 합 구하기 (0) | 2019.10.03 |
[OpenCV] Color K-Means (0) | 2019.10.02 |
[OpenCV] 이미지 합치기 (0) | 2019.10.02 |