From a0efc139fd4faee64118d59d6a42e714188acf1e Mon Sep 17 00:00:00 2001 From: charlie <1753524606@qq.com> Date: Fri, 22 Jul 2022 17:19:03 +0800 Subject: [PATCH] =?UTF-8?q?=E5=9F=BA=E7=A1=80=E9=83=A8=E5=88=86=E5=AE=8C?= =?UTF-8?q?=E6=88=90=EF=BC=8C=E5=B9=B6=E9=87=8D=E6=9E=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- basic/helper.py | 570 ++++++++++++++++++++++++++++++++++ basic/urls.py | 2 +- basic/views.py | 802 +++++------------------------------------------- 3 files changed, 652 insertions(+), 722 deletions(-) create mode 100644 basic/helper.py diff --git a/basic/helper.py b/basic/helper.py new file mode 100644 index 0000000..867b0b7 --- /dev/null +++ b/basic/helper.py @@ -0,0 +1,570 @@ +import math +import random +import uuid + +import cv2 +import matplotlib.pyplot as plt +import numpy as np +from django.http import HttpResponse + +PREFIX = 'media/' + +DEFAULT_FORMAT = '.jpg' + +SUPPORT_FILE_FORMAT = ['png', 'jpg', 'bmp', 'jpeg', 'jpe', 'dib', 'pbm', 'pgm', 'ppm', 'tiff', 'tif'] + + +def get_image_name(): + return uuid.uuid1().__str__() + + +def get_image(request): + file = request.FILES.get('image') + suffix = file.name[file.name.rfind('.') + 1:].lower() + if suffix not in SUPPORT_FILE_FORMAT: + return '' + filename = get_image_name() + '.' + suffix + img = open(PREFIX + filename, 'wb+') + for chunk in file.chunks(): + img.write(chunk) + img.close() + return filename + + +def process_bg(): + img = np.zeros((800, 800, 3), np.uint8) + return save_image(img) + + +def process_line(para): + name, start, end, color, thickness = para['img'], para['start'], para['end'], para['color'], para['thickness'] + img = cv2.imread(PREFIX + name) + cv2.line(img, tuple(start), tuple(end), tuple(color), thickness) + cv2.imwrite(PREFIX + name, img) + return name + + +def process_rectangle(para): + name, start, end, color, thickness = para['img'], para['start'], para['end'], para['color'], para['thickness'] + img = cv2.imread(PREFIX + name) + cv2.rectangle(img, tuple(start), tuple(end), tuple(color), thickness) + cv2.imwrite(PREFIX + name, img) + return name + + +def process_circle(para): + name, center, radius, color, thickness = para['img'], para['center'], para['radius'], para['color'], para[ + 'thickness'] + img = cv2.imread(PREFIX + name) + cv2.circle(img, tuple(center), radius, tuple(color), thickness) + cv2.imwrite(PREFIX + name, img) + return name + + +def process_ellipse(para): + name, center, axes, angle, startangle, endangle, color, thickness = para['img'], para['center'], para['axes'], para[ + 'angle'], para['startangle'], para['endangle'], para['color'], para['thickness'] + img = cv2.imread(PREFIX + name) + cv2.ellipse(img, tuple(center), tuple(axes), angle, startangle, endangle, tuple(color), thickness) + cv2.imwrite(PREFIX + name, img) + return name + + +def process_polylines(para): + name, point, isclosed, color = para['img'], para['point'], para['isclosed'], para['color'] + img = cv2.imread(PREFIX + name) + pts = np.array(point, np.int32) + pts = pts.reshape((-1, 1, 2)) + cv2.polylines(img, [pts], isclosed, tuple(color)) + cv2.imwrite(PREFIX + name, img) + return name + + +def process_text(para): + name, text, org, fontsize, color = para['img'], para['text'], para['org'], para['fontsize'], para['color'] + img = cv2.imread(PREFIX + name) + cv2.putText(img, text, org, fontFace=cv2.FONT_HERSHEY_SCRIPT_COMPLEX, fontScale=fontsize, color=tuple(color)) + cv2.imwrite(PREFIX + name, img) + return name + + +def process_filter_rgb(para, data): + limit = para.get('limit', 100) + c_range = para.get('range', [90, 230]) + if np.max(data) > limit: + data = data * (255 / np.max(data)) + tmp = np.zeros_like(data) + tmp[((data > c_range[0]) & (data <= c_range[1]))] = 255 + return tmp + + +def base2read(img, has_color): + img[0], img[1] = img[1], img[0] + img1 = cv2.imread(PREFIX + img[0], has_color) + img2 = cv2.imread(PREFIX + img[1], has_color) + rows, cols = img1.shape[:2] + img2 = cv2.resize(img2, (cols, rows), interpolation=cv2.INTER_CUBIC) + return img1, img2 + + +def logic_and(img, has_color, base): + img1 = None + img2 = None + if base == 2: + img1, img2 = base2read(img, has_color) + ret = img1 & img2 + return save_image(ret) + + +def logic_or(img, has_color, base): + img1 = None + img2 = None + if base == 2: + img1, img2 = base2read(img, has_color) + ret = img1 | img2 + return save_image(ret) + + +def logic_not(img, has_color, base): + if base == 2: + img[0], img[1] = img[1], img[0] + image = cv2.imread(PREFIX + img[0], has_color) + ret = ~image + return save_image(ret) + + +def arithmetic_add(img, has_color, base): + img1 = None + img2 = None + if base == 2: + img1, img2 = base2read(img, has_color) + ret = cv2.add(img1, img2) + return save_image(ret) + + +def base2read_choice(img, has_color, base): + img1 = cv2.imread(PREFIX + img[0], has_color) + img2 = cv2.imread(PREFIX + img[1], has_color) + if base == 1: + rows, cols = img1.shape[:2] + img2 = cv2.resize(img2, (cols, rows), interpolation=cv2.INTER_CUBIC) + elif base == 2: + rows, cols = img2.shape[:2] + img1 = cv2.resize(img1, (cols, rows), interpolation=cv2.INTER_CUBIC) + return img1, img2 + + +def arithmetic_sub(img, has_color, base): + img1, img2 = base2read_choice(img, has_color, base) + ret = cv2.subtract(img1, img2) + return save_image(ret) + + +def arithmetic_multi(img, has_color, base): + img1 = None + img2 = None + if base == 2: + img1, img2 = base2read(img, has_color) + ret = cv2.multiply(img1, img2) + return save_image(ret) + + +def arithmetic_div(img, has_color, base): + img1, img2 = base2read_choice(img, has_color, base) + ret = cv2.divide(img1, img2) + return save_image(ret) + + +def rotate_bound(image, angle): + (h, w) = image.shape[:2] + (cX, cY) = (w // 2, h // 2) + M = cv2.getRotationMatrix2D((cX, cY), -angle, 1.0) + cos = np.abs(M[0, 0]) + sin = np.abs(M[0, 1]) + nW = int((h * sin) + (w * cos)) + nH = int((h * cos) + (w * sin)) + M[0, 2] += (nW / 2) - cX + M[1, 2] += (nH / 2) - cY + return cv2.warpAffine(image, M, (nW, nH)) + + +def hist_cover_gray(img, fileName): + plt.figure(fileName, figsize=(16, 8)) + hist = cv2.calcHist([img], [0], None, [256], [0, 255]) + plt.plot(hist) + plt.xlim([0, 255]) + plt.savefig(fileName) + + +def hist_cover_rgb(img, fileName): + color = ["r", "g", "b"] + b, g, r = cv2.split(img) + img = cv2.merge([r, g, b]) + for index, c in enumerate(color): + hist = cv2.calcHist([img], [index], None, [256], [0, 255]) + plt.plot(hist, color=c) + plt.xlim([0, 255]) + plt.savefig(fileName) + + +def grayHist(img, filename): + plt.figure(filename, figsize=(16, 8)) + h, w = img.shape[:2] + pixelSequence = img.reshape(h * w, 1) + numberBins = 256 + histogram_, bins, patch = plt.hist(pixelSequence, numberBins) + plt.xlabel("gray label") + plt.ylabel("number of pixels") + plt.axis([0, 255, 0, np.max(histogram_)]) + plt.savefig(filename) + + +def process_LoG(img): + grayImage = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) + img = cv2.copyMakeBorder(grayImage, 2, 2, 2, 2, borderType=cv2.BORDER_REPLICATE) + img = cv2.GaussianBlur(img, (3, 3), 0, 0) + m1 = np.array( + [[0, 0, -1, 0, 0], [0, -1, -2, -1, 0], [-1, -2, 16, -2, -1], [0, -1, -2, -1, 0], [0, 0, -1, 0, 0]], + dtype=np.int32) + image1 = np.zeros(img.shape).astype(np.int32) + h, w, _ = img.shape + for i in range(2, h - 2): + for j in range(2, w - 2): + image1[i, j] = np.sum(m1 * img[i - 2:i + 3, j - 2:j + 3, 1]) + return cv2.convertScaleAbs(image1) + + +def process_Canny(img): + tmp = cv2.GaussianBlur(img, (3, 3), 0) + gradx = cv2.Sobel(tmp, cv2.CV_16SC1, 1, 0) + grady = cv2.Sobel(tmp, cv2.CV_16SC1, 0, 1) + return cv2.Canny(gradx, grady, 50, 150) + + +def process_enhance(img): + h, w = img.shape + gradient = np.zeros((h, w)) + img = img.astype('float') + for i in range(h - 1): + for j in range(w - 1): + gx = abs(img[i + 1, j] - img[i, j]) + gy = abs(img[i, j + 1] - img[i, j]) + gradient[i, j] = gx + gy + sharp = img + gradient + sharp = np.where(sharp > 255, 255, sharp) + sharp = np.where(sharp < 0, 0, sharp) + gradient = gradient.astype('uint8') + sharp = sharp.astype('uint8') + ret = [{"sharp": save_image(sharp), "gradient": save_image(gradient)}] + return HttpResponse(ret) + + +def process_lcd_with_p(edges, img): + linesP = cv2.HoughLinesP(edges, 1, np.pi / 180, 80, 200, 15) + for i_P in linesP: + for x1, y1, x2, y2 in i_P: + cv2.line(img, (x1, y1), (x2, y2), (0, 255, 0), 3) + return img + + +def process_lcd_without_p(edges, img): + lines = cv2.HoughLines(edges, 1, np.pi / 2, 118) + for i_line in lines: + for line in i_line: + rho = line[0] + theta = line[1] + if (theta < (np.pi / 4.)) or (theta > (3. * np.pi / 4.0)): # 垂直直线 + pt1 = (int(rho / np.cos(theta)), 0) + pt2 = (int((rho - img.shape[0] * np.sin(theta)) / np.cos(theta)), img.shape[0]) + cv2.line(img, pt1, pt2, (0, 0, 255)) + else: + pt1 = (0, int(rho / np.sin(theta))) + pt2 = (img.shape[1], int((rho - img.shape[1] * np.cos(theta)) / np.sin(theta))) + cv2.line(img, pt1, pt2, (0, 0, 255), 1) + return img + + +def ideal_low_filter(img, D0): + h, w = img.shape[:2] + filter_img = np.ones((h, w)) + u = np.fix(h / 2) + v = np.fix(w / 2) + for i in range(h): + for j in range(w): + d = np.sqrt((i - u) ** 2 + (j - v) ** 2) + filter_img[i, j] = 0 if d > D0 else 1 + return filter_img + + +def ideal_high_pass_filter(img, D0): + h, w = img.shape[:2] + filter_img = np.zeros((h, w)) + u = np.fix(h / 2) + v = np.fix(w / 2) + for i in range(h): + for j in range(w): + d = np.sqrt((i - u) ** 2 + (j - v) ** 2) + filter_img[i, j] = 0 if d < D0 else 1 + return filter_img + + +def butterworth_low_pass_filter(img, D0, rank): + h, w = img.shape[:2] + filter_img = np.zeros((h, w)) + u = np.fix(h / 2) + v = np.fix(w / 2) + for i in range(h): + for j in range(w): + d = np.sqrt((i - u) ** 2 + (j - v) ** 2) + filter_img[i, j] = 1 / (1 + ((d / D0) ** (2 * rank))) + return filter_img + + +def butterworth_high_pass_filter(img, D0, rank): + h, w = img.shape[:2] + filter_img = np.zeros((h, w)) + u = np.fix(h / 2) + v = np.fix(w / 2) + for i in range(h): + for j in range(w): + d = np.sqrt((i - u) ** 2 + (j - v) ** 2) + filter_img[i, j] = 1 / (1 + ((D0 / d) ** (2 * rank))) + return filter_img + + +def gauss_low_pass_filter(img, d0): + h, w = img.shape[:2] + filter_img = np.zeros((h, w)) + u = np.fix(h / 2) + v = np.fix(w / 2) + for i in range(h): + for j in range(w): + d = np.sqrt((i - u) ** 2 + (j - v) ** 2) + filter_img[i, j] = np.exp(-0.5 * (d ** 2) / (d0 ** 2)) + return filter_img + + +def gauss_high_pass_filter(img, d0): + h, w = img.shape[:2] + filter_img = np.zeros((h, w)) + u = np.fix(h / 2) + v = np.fix(w / 2) + for i in range(h): + for j in range(w): + d = np.sqrt((i - u) ** 2 + (j - v) ** 2) + filter_img[i, j] = 1 - np.exp(-0.5 * (d ** 2) / (d0 ** 2)) + return filter_img + + +def filter_use_smooth(img, my_filter): + # 首先进行傅里叶变换 + f = np.fft.fft2(img) + f_center = np.fft.fftshift(f) + # 应用滤波器进行反变换 + S = np.multiply(f_center, my_filter) # 频率相乘——l(u,v)*H(u,v) + f_origin = np.fft.ifftshift(S) # 将低频移动到原来的位置 + f_origin = np.fft.ifft2(f_origin) # 使用ifft2进行傅里叶的逆变换 + f_origin = np.abs(f_origin) # 设置区间 + return f_origin + + +def filter_use_sharpen(img, my_filter): + f_origin = filter_use_smooth(img, my_filter) + f_origin = f_origin / np.max(f_origin.all()) + return f_origin + + +def process_roberts(img): + kernelx = np.array([[-1, 0], [0, 1]], dtype=int) + kernely = np.array([[0, -1], [1, 0]], dtype=int) + x = cv2.filter2D(img, cv2.CV_16S, kernelx) + y = cv2.filter2D(img, cv2.CV_16S, kernely) + # 转uint8 + absX = cv2.convertScaleAbs(x) + absY = cv2.convertScaleAbs(y) + return cv2.addWeighted(absX, 0.5, absY, 0.5, 0) + + +def process_sobel(img): + x = cv2.Sobel(img, cv2.CV_16S, 1, 0) # 对x求一阶导 + y = cv2.Sobel(img, cv2.CV_16S, 0, 1) # 对y求一阶导 + absX = cv2.convertScaleAbs(x) + absY = cv2.convertScaleAbs(y) + return cv2.addWeighted(absX, 0.5, absY, 0.5, 0) + + +def process_prewitt(img): + kernelx = np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]], dtype=int) + kernely = np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]], dtype=int) + x = cv2.filter2D(img, cv2.CV_16S, kernelx) + y = cv2.filter2D(img, cv2.CV_16S, kernely) + # 转uint8 + absX = cv2.convertScaleAbs(x) + absY = cv2.convertScaleAbs(y) + return cv2.addWeighted(absX, 0.5, absY, 0.5, 0) + + +def process_laplacian(img): + dst = cv2.Laplacian(img, cv2.CV_16S, ksize=3) + return cv2.convertScaleAbs(dst) + + +def process_gauss_noise(img): + img = np.array(img / 255, dtype=float) + noise_ = np.random.normal(0, 0.1, img.shape) + img = img + noise_ + img = np.clip(img, 0.0, 1.0) + return np.uint8(img * 255) + + +def process_salt_and_peper_noise(img, para): + range_salt = para.get('salt', 0.2) + range_peper = para.get('peper', 0.8) + output = np.zeros(img.shape, np.uint8) + for i in range(img.shape[0]): + for j in range(img.shape[1]): + rdn = random.random() + if rdn < range_salt: + output[i][j] = 0 + elif rdn > range_peper: + output[i][j] = 255 + else: + output[i][j] = img[i][j] + return output + + +def process_geometric_mean(img): + output = np.zeros(img.shape, np.uint8) + for i in range(img.shape[0]): + for j in range(img.shape[1]): + ji = 1.0 + for m in range(-1, 2): + if 0 <= j + m < img.shape[1]: + ji *= img[i][j + m] + output[i][j] = math.pow(ji, 1 / 3) + return output + + +def process_arithmetic_mean(img): + output = np.zeros(img.shape, np.uint8) + for i in range(img.shape[0]): + for j in range(img.shape[1]): + my_sum = 0 + for m in range(-1, 2): + for n in range(-1, 2): + if 0 <= i + m < img.shape[0] and 0 <= j + n < img.shape[1]: + my_sum += img[i + m][j + n] + output[i][j] = int(my_sum / 9) + return output + + +def process_harmonic_filter(img): + output = np.zeros(img.shape, np.uint8) + for i in range(img.shape[0]): + for j in range(img.shape[1]): + my_sum = 0 + for m in range(-1, 2): + for n in range(-1, 2): + if 0 <= i + m < img.shape[0] and 0 <= j + n < img.shape[1]: + my_sum += 1 / img[i + m][j + n] + output[i][j] = int(9 / my_sum) + return output + + +def get_middle(array): + length = len(array) + for i in range(length): + for j in range(i + 1, length): + if array[j] > array[i]: + temp = array[j] + array[j] = array[i] + array[i] = temp + return array[int(length / 2)] + + +def get_array_from_struct_ele(img, i, j): + array = [] + for m in range(-1, 2): + for n in range(-1, 2): + if 0 <= i + m < img.shape[0] and 0 <= j + n < img.shape[1]: + array.append(img[i + m][j + n]) + return array + + +def process_max_sort(img): + output = np.zeros(img.shape, np.uint8) + for i in range(img.shape[0]): + for j in range(img.shape[1]): + array = get_array_from_struct_ele(img, i, j) + array.sort(reverse=True) + output[i][j] = max(array[0], img[i][j]) + return output + + +def process_min_sort(img): + output = np.zeros(img.shape, np.uint8) + for i in range(img.shape[0]): + for j in range(img.shape[1]): + array = get_array_from_struct_ele(img, i, j) + array.sort() + output[i][j] = min(array[0], img[i][j]) + return output + + +def process_median_sort(img): + output = np.zeros(img.shape, np.uint8) + for i in range(img.shape[0]): + for j in range(img.shape[1]): + array = get_array_from_struct_ele(img, i, j) + output[i][j] = get_middle(array) + return output + + +def process_high_choice(img, limit): + output = np.zeros(img.shape, np.uint8) + for i in range(img.shape[0]): + for j in range(img.shape[1]): + if img[i][j] > limit: + output[i][j] = img[i][j] + else: + output[i][j] = 0 + return output + + +def process_low_choice(img, limit): + output = np.zeros(img.shape, np.uint8) + for i in range(img.shape[0]): + for j in range(img.shape[1]): + if img[i][j] < limit: + output[i][j] = img[i][j] + else: + output[i][j] = 0 + return output + + +def process_pass_choice(img, my_min, my_max): + output = np.zeros(img.shape, np.uint8) + for i in range(img.shape[0]): + for j in range(img.shape[1]): + if my_min < img[i][j] < my_max: + output[i][j] = img[i][j] + else: + output[i][j] = 255 + return output + + +def process_stop_choice(img, my_min, my_max): + output = np.zeros(img.shape, np.uint8) + for i in range(img.shape[0]): + for j in range(img.shape[1]): + if my_min < img[i][j] < my_max: + output[i][j] = 0 + else: + output[i][j] = img[i][j] + return output + + +def save_image(img): + img_name = get_image_name() + DEFAULT_FORMAT + cv2.imwrite(PREFIX + img_name, img) + return img_name diff --git a/basic/urls.py b/basic/urls.py index fe45ec1..71c2dcb 100644 --- a/basic/urls.py +++ b/basic/urls.py @@ -4,7 +4,7 @@ from . import views urlpatterns = [ path('upload/', views.upload), - path('', views.r), + path('', views.load), path('draw', views.basic_drawing), path('hsv/', views.hsv_color_space), path('rgb/', views.rgb_color_space), diff --git a/basic/views.py b/basic/views.py index bb7a0f4..49371dd 100644 --- a/basic/views.py +++ b/basic/views.py @@ -1,113 +1,26 @@ import json -import math -import random -import uuid -import cv2 -import matplotlib.pyplot as plt -import numpy as np -from django.http import HttpResponse from django.shortcuts import render -# Create your views here. from django.views.decorators.csrf import csrf_exempt from pywt import dwt2, idwt2 +from .helper import * + PREFIX = 'media/' DEFAULT_FORMAT = '.jpg' -SUPPORT_FILE_FORMAT = ['png', 'jpg', 'bmp', 'jpeg', 'jpe', 'dib', 'pbm', 'pgm', 'ppm', 'tiff', 'tif'] - - -# 获取uuid图片名 -def getImageName(): - return uuid.uuid1().__str__() - -# 保存图片,并判断是否为合适的扩展名 -def getImage(request): - print(request.FILES) - file = request.FILES.get('image') - suffix = file.name[file.name.rfind('.') + 1:].lower() - if suffix not in SUPPORT_FILE_FORMAT: - return '' - filename = getImageName() + '.' + suffix - img = open(PREFIX + filename, 'wb+') - for chunk in file.chunks(): - img.write(chunk) - img.close() - return filename - - -# 接收图片,转发到getImage @csrf_exempt def upload(request): - imageName = getImage(request) - if imageName == '': - return HttpResponse('Not supported image format') - return HttpResponse(imageName) - - -def process_bg(): - img = np.zeros((800, 800, 3), np.uint8) - filename = getImageName() + DEFAULT_FORMAT - cv2.imwrite(PREFIX + filename, img) - return filename - - -def process_line(para): - name, start, end, color, thickness = para['img'], para['start'], para['end'], para['color'], para['thickness'] - img = cv2.imread(PREFIX + name) - cv2.line(img, tuple(start), tuple(end), tuple(color), thickness) - cv2.imwrite(PREFIX + name, img) - return name - - -def process_rectangle(para): - name, start, end, color, thickness = para['img'], para['start'], para['end'], para['color'], para['thickness'] - img = cv2.imread(PREFIX + name) - cv2.rectangle(img, tuple(start), tuple(end), tuple(color), thickness) - cv2.imwrite(PREFIX + name, img) - return name - - -def process_circle(para): - name, center, radius, color, thickness = para['img'], para['center'], para['radius'], para['color'], para[ - 'thickness'] - img = cv2.imread(PREFIX + name) - cv2.circle(img, tuple(center), radius, tuple(color), thickness) - cv2.imwrite(PREFIX + name, img) - return name - - -def process_ellipse(para): - name, center, axes, angle, startangle, endangle, color, thickness = para['img'], para['center'], para['axes'], para[ - 'angle'], para['startangle'], para['endangle'], para['color'], para['thickness'] - img = cv2.imread(PREFIX + name) - cv2.ellipse(img, tuple(center), tuple(axes), angle, startangle, endangle, tuple(color), thickness) - cv2.imwrite(PREFIX + name, img) - return name - - -def process_polylines(para): - name, point, isclosed, color = para['img'], para['point'], para['isclosed'], para['color'] - img = cv2.imread(PREFIX + name) - pts = np.array(point, np.int32) - pts = pts.reshape((-1, 1, 2)) - cv2.polylines(img, [pts], isclosed, tuple(color)) - cv2.imwrite(PREFIX + name, img) - return name - - -def process_text(para): - name, text, org, fontsize, color = para['img'], para['text'], para['org'], para['fontsize'], para['color'] - img = cv2.imread(PREFIX + name) - cv2.putText(img, text, org, fontFace=cv2.FONT_HERSHEY_SCRIPT_COMPLEX, fontScale=fontsize, color=tuple(color)) - cv2.imwrite(PREFIX + name, img) - return name + if request.method == 'POST': + imageName = get_image(request) + if imageName == '': + return HttpResponse('Not supported image format') + return HttpResponse(imageName) + return HttpResponse('Please use POST') -# 使用opencv 基本绘图 @csrf_exempt def basic_drawing(request): if request.method == 'POST': @@ -128,17 +41,7 @@ def basic_drawing(request): return HttpResponse(process_polylines(para)) elif draw_type == 'text': return HttpResponse(process_text(para)) - return HttpResponse('请使用POST方法') - - -def process_filter_rgb(para, data): - limit = para.get('limit', 100) - c_range = para.get('range', [90, 230]) - if np.max(data) > limit: - data = data * (255 / np.max(data)) - tmp = np.zeros_like(data) - tmp[((data > c_range[0]) & (data <= c_range[1]))] = 255 - return tmp + return HttpResponse('Please use POST') @csrf_exempt @@ -159,7 +62,7 @@ def rgb_color_space(request, color): filename = color + '-' + image_name cv2.imwrite(PREFIX + filename, data) return HttpResponse(filename) - return HttpResponse('请使用POST方法') + return HttpResponse('Please use POST') @csrf_exempt @@ -183,99 +86,7 @@ def hsv_color_space(request, color): filename = color + '-' + image_name cv2.imwrite(PREFIX + filename, data) return HttpResponse(filename) - return HttpResponse('请使用POST方法') - - -def logic_and(img, has_color, base): - if base == 2: - img[0], img[1] = img[1], img[0] - img1 = cv2.imread(PREFIX + img[0], has_color) - img2 = cv2.imread(PREFIX + img[1], has_color) - rows, cols = img1.shape[:2] - img2 = cv2.resize(img2, (cols, rows), interpolation=cv2.INTER_CUBIC) - ret = img1 & img2 - filename = getImageName() + DEFAULT_FORMAT - cv2.imwrite(PREFIX + filename, ret) - return filename - - -def logic_or(img, has_color, base): - if base == 2: - img[0], img[1] = img[1], img[0] - img1 = cv2.imread(PREFIX + img[0], has_color) - img2 = cv2.imread(PREFIX + img[1], has_color) - rows, cols = img1.shape[:2] - img2 = cv2.resize(img2, (cols, rows), interpolation=cv2.INTER_CUBIC) - ret = img1 | img2 - filename = getImageName() + DEFAULT_FORMAT - cv2.imwrite(PREFIX + filename, ret) - return filename - - -def logic_not(img, has_color, base): - if base == 2: - img[0], img[1] = img[1], img[0] - image = cv2.imread(PREFIX + img[0], has_color) - ret = ~image - filename = getImageName() + DEFAULT_FORMAT - cv2.imwrite(PREFIX + filename, ret) - return filename - - -def arithmetic_add(img, has_color, base): - if base == 2: - img[0], img[1] = img[1], img[0] - img1 = cv2.imread(PREFIX + img[0], has_color) - img2 = cv2.imread(PREFIX + img[1], has_color) - rows, cols = img1.shape[:2] - img2 = cv2.resize(img2, (cols, rows), interpolation=cv2.INTER_CUBIC) - ret = cv2.add(img1, img2) - filename = getImageName() + DEFAULT_FORMAT - cv2.imwrite(PREFIX + filename, ret) - return filename - - -def arithmetic_sub(img, has_color, base): - img1 = cv2.imread(PREFIX + img[0], has_color) - img2 = cv2.imread(PREFIX + img[1], has_color) - if base == 1: - rows, cols = img1.shape[:2] - img2 = cv2.resize(img2, (cols, rows), interpolation=cv2.INTER_CUBIC) - elif base == 2: - rows, cols = img2.shape[:2] - img1 = cv2.resize(img1, (cols, rows), interpolation=cv2.INTER_CUBIC) - ret = cv2.subtract(img1, img2) - filename = getImageName() + DEFAULT_FORMAT - cv2.imwrite(PREFIX + filename, ret) - return filename - - -def arithmetic_multi(img, has_color, base): - if base == 2: - img[0], img[1] = img[1], img[0] - img1 = cv2.imread(PREFIX + img[0], has_color) - img2 = cv2.imread(PREFIX + img[1], has_color) - rows, cols = img1.shape[:2] - img2 = cv2.resize(img2, (cols, rows), interpolation=cv2.INTER_CUBIC) - ret = cv2.multiply(img1, img2) - filename = getImageName() + DEFAULT_FORMAT - cv2.imwrite(PREFIX + filename, ret) - return filename - - -def arithmetic_div(img, has_color, base): - img1 = cv2.imread(PREFIX + img[0], has_color) - img2 = cv2.imread(PREFIX + img[1], has_color) - if base == 1: - rows, cols = img1.shape[:2] - img2 = cv2.resize(img2, (cols, rows), interpolation=cv2.INTER_CUBIC) - elif base == 2: - rows, cols = img2.shape[:2] - img1 = cv2.resize(img1, (cols, rows), interpolation=cv2.INTER_CUBIC) - ret = cv2.divide(img1, img2) - filename = getImageName() + DEFAULT_FORMAT - cv2.imwrite(PREFIX + filename, ret) - return filename + return HttpResponse('Please use POST') @csrf_exempt @@ -300,7 +111,7 @@ def basic_operation(request): return HttpResponse(arithmetic_multi(img, has_color, base)) elif operator == 'div': return HttpResponse(arithmetic_div(img, has_color, base)) - return HttpResponse('请使用POST方法') + return HttpResponse('Please use POST') @csrf_exempt @@ -311,9 +122,7 @@ def resize(request): img = cv2.imread(PREFIX + image) size = para.get('size', None) if size is not None: - width = img.shape[0] - height = img.shape[1] - interpolation = None + height, width = img.shape[:2] if width * height >= size[0] * size[1]: interpolation = cv2.INTER_AREA else: @@ -326,23 +135,8 @@ def resize(request): else: interpolation = cv2.INTER_CUBIC img = cv2.resize(img, (0, 0), fx=multiple, fy=multiple, interpolation=interpolation) - new_filename = getImageName() + DEFAULT_FORMAT - cv2.imwrite(PREFIX + new_filename, img) - return HttpResponse(new_filename) - return HttpResponse('请使用POST方法') - - -def rotate_bound(image, angle): - (h, w) = image.shape[:2] - (cX, cY) = (w // 2, h // 2) - M = cv2.getRotationMatrix2D((cX, cY), -angle, 1.0) - cos = np.abs(M[0, 0]) - sin = np.abs(M[0, 1]) - nW = int((h * sin) + (w * cos)) - nH = int((h * cos) + (w * sin)) - M[0, 2] += (nW / 2) - cX - M[1, 2] += (nH / 2) - cY - return cv2.warpAffine(image, M, (nW, nH)) + return HttpResponse(save_image(img)) + return HttpResponse('Please use POST') @csrf_exempt @@ -353,10 +147,8 @@ def rotate(request): img = cv2.imread(PREFIX + image) angle = para['angle'] img = rotate_bound(img, angle) - filename = getImageName() + DEFAULT_FORMAT - cv2.imwrite(PREFIX + filename, img) - return HttpResponse(filename) - return HttpResponse('请使用POST方法') + return HttpResponse(save_image(img)) + return HttpResponse('Please use POST') @csrf_exempt @@ -369,10 +161,8 @@ def translation(request): height, width = img.shape[:2] M = np.float32([[1, 0, offset[0]], [0, 1, offset[1]]]) img = cv2.warpAffine(img, M, (width, height)) - filename = getImageName() + DEFAULT_FORMAT - cv2.imwrite(PREFIX + filename, img) - return HttpResponse(filename) - return HttpResponse('请使用POST方法') + return HttpResponse(save_image(img)) + return HttpResponse('Please use POST') @csrf_exempt @@ -383,10 +173,8 @@ def flip(request): img = cv2.imread(PREFIX + image) flip_code = para.get('flip', 1) img = cv2.flip(img, flip_code) - filename = getImageName() + DEFAULT_FORMAT - cv2.imwrite(PREFIX + filename, img) - return HttpResponse(filename) - return HttpResponse('请使用POST方法') + return HttpResponse(save_image(img)) + return HttpResponse('Please use POST') @csrf_exempt @@ -400,29 +188,8 @@ def affine(request): rows, cols = img.shape[:2] M = cv2.getAffineTransform(before, after) img = cv2.warpAffine(img, M, (rows, cols)) - filename = getImageName() + DEFAULT_FORMAT - cv2.imwrite(PREFIX + filename, img) - return HttpResponse(filename) - return HttpResponse('请使用POST方法') - - -def hist_cover_gray(img, fileName): - plt.figure(fileName, figsize=(16, 8)) - hist = cv2.calcHist([img], [0], None, [256], [0, 255]) - plt.plot(hist) - plt.xlim([0, 255]) - plt.savefig(fileName) - - -def hist_cover_rgb(img, fileName): - color = ["r", "g", "b"] - b, g, r = cv2.split(img) - img = cv2.merge([r, g, b]) - for index, c in enumerate(color): - hist = cv2.calcHist([img], [index], None, [256], [0, 255]) - plt.plot(hist, color=c) - plt.xlim([0, 255]) - plt.savefig(fileName) + return HttpResponse(save_image(img)) + return HttpResponse('Please use POST') @csrf_exempt @@ -430,9 +197,8 @@ def histogram(request): if request.method == 'POST': para = json.loads(request.body) image = para['img'] - color = para['color'] - histogram_name = getImageName() + DEFAULT_FORMAT + histogram_name = get_image_name() + DEFAULT_FORMAT if color: img = cv2.imread(PREFIX + image) hist_cover_rgb(img, PREFIX + histogram_name) @@ -440,20 +206,7 @@ def histogram(request): img = cv2.imread(PREFIX + image, 0) hist_cover_gray(img, PREFIX + histogram_name) return HttpResponse(histogram_name) - return HttpResponse('请使用POST方法') - - -def grayHist(img, filename): - plt.figure(filename, figsize=(16, 8)) - h, w = img.shape[:2] - pixelSequence = img.reshape(h * w, 1) - numberBins = 256 - histogram, bins, patch = plt.hist(pixelSequence, numberBins) - plt.xlabel("gray label") - plt.ylabel("number of pixels") - plt.axis([0, 255, 0, np.max(histogram)]) - # 打印输出峰值 - plt.savefig(filename) + return HttpResponse('Please use POST') @csrf_exempt @@ -463,9 +216,9 @@ def piecewise_linear_transform(request): image = para['img'] img = cv2.imread(PREFIX + image, 0) funcs = para['func'] - ret_name1 = getImageName() + DEFAULT_FORMAT - ret_name2 = getImageName() + DEFAULT_FORMAT - out_name = getImageName() + DEFAULT_FORMAT + ret_name1 = get_image_name() + DEFAULT_FORMAT + ret_name2 = get_image_name() + DEFAULT_FORMAT + out_name = get_image_name() + DEFAULT_FORMAT h, w = img.shape[:2] out = np.zeros(img.shape, np.uint8) for i in range(h): @@ -488,7 +241,7 @@ def piecewise_linear_transform(request): grayHist(img, PREFIX + ret_name1) grayHist(out, PREFIX + ret_name2) return HttpResponse([{"orig": image, "hist": ret_name1}, {"orig": out_name, "hist": ret_name2}]) - return HttpResponse('请使用POST方法') + return HttpResponse('Please use POST') @csrf_exempt @@ -499,67 +252,21 @@ def edge_detection(request): img = cv2.imread(PREFIX + image, 0) operator = para['operator'] if operator == 'Roberts': - kernelx = np.array([[-1, 0], [0, 1]], dtype=int) - kernely = np.array([[0, -1], [1, 0]], dtype=int) - x = cv2.filter2D(img, cv2.CV_16S, kernelx) - y = cv2.filter2D(img, cv2.CV_16S, kernely) - absX = cv2.convertScaleAbs(x) - absY = cv2.convertScaleAbs(y) - img = cv2.addWeighted(absX, 0.5, absY, 0.5, 0) + img = process_roberts(img) elif operator == 'Sobel': - x = cv2.Sobel(img, cv2.CV_16S, 1, 0) - y = cv2.Sobel(img, cv2.CV_16S, 0, 1) - absX = cv2.convertScaleAbs(x) - absY = cv2.convertScaleAbs(y) - img = cv2.addWeighted(absX, 0.5, absY, 0.5, 0) + img = process_sobel(img) elif operator == 'Laplacian': img_gaussianBlur = cv2.GaussianBlur(img, (5, 5), 0) - dst = cv2.Laplacian(img_gaussianBlur, cv2.CV_16S, ksize=3) - img = cv2.convertScaleAbs(dst) + img = process_laplacian(img_gaussianBlur) elif operator == 'LoG': - grayImage = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) - img = cv2.copyMakeBorder(grayImage, 2, 2, 2, 2, borderType=cv2.BORDER_REPLICATE) - img = cv2.GaussianBlur(img, (3, 3), 0, 0) - m1 = np.array( - [[0, 0, -1, 0, 0], [0, -1, -2, -1, 0], [-1, -2, 16, -2, -1], [0, -1, -2, -1, 0], [0, 0, -1, 0, 0]], - dtype=np.int32) - image1 = np.zeros(img.shape).astype(np.int32) - h, w, _ = img.shape - for i in range(2, h - 2): - for j in range(2, w - 2): - image1[i, j] = np.sum(m1 * img[i - 2:i + 3, j - 2:j + 3, 1]) - img = cv2.convertScaleAbs(image1) + img = process_LoG(img) elif operator == 'Canny': - tmp = cv2.GaussianBlur(img, (3, 3), 0) - # 3. 求x,y方向的Sobel算子 - gradx = cv2.Sobel(tmp, cv2.CV_16SC1, 1, 0) - grady = cv2.Sobel(tmp, cv2.CV_16SC1, 0, 1) - # 4. 使用Canny函数处理图像,x,y分别是3求出来的梯度,低阈值50,高阈值150 - img = cv2.Canny(gradx, grady, 50, 150) + img = process_Canny(img) + # 这里由于返回格式的不同,会在process_enhance之中直接返回,不在往后执行 elif operator == 'Enhance': - h, w = img.shape - gradient = np.zeros((h, w)) - img = img.astype('float') - for i in range(h - 1): - for j in range(w - 1): - gx = abs(img[i + 1, j] - img[i, j]) - gy = abs(img[i, j + 1] - img[i, j]) - gradient[i, j] = gx + gy - sharp = img + gradient - sharp = np.where(sharp > 255, 255, sharp) - sharp = np.where(sharp < 0, 0, sharp) - gradient = gradient.astype('uint8') - sharp = sharp.astype('uint8') - sharp_name = getImageName() + DEFAULT_FORMAT - gradient_name = getImageName() + DEFAULT_FORMAT - cv2.imwrite(PREFIX + sharp_name, sharp) - cv2.imwrite(PREFIX + gradient_name, gradient) - ret = [{"sharp": sharp_name, "gradient": gradient_name}] - return HttpResponse(ret) - filename = getImageName() + DEFAULT_FORMAT - cv2.imwrite(PREFIX + filename, img) - return HttpResponse(filename) - return HttpResponse('请使用POST方法') + process_enhance(img) + return HttpResponse(save_image(img)) + return HttpResponse('Please use POST') @csrf_exempt @@ -569,146 +276,14 @@ def line_change_detection(request): image = para['img'] img = cv2.imread(PREFIX + image) use_p = para['use_p'] - img = cv2.GaussianBlur(img, (3, 3), 0) edges = cv2.Canny(img, 50, 150, apertureSize=3) if use_p: - linesP = cv2.HoughLinesP(edges, 1, np.pi / 180, 80, 200, 15) - for i_P in linesP: - for x1, y1, x2, y2 in i_P: - cv2.line(img, (x1, y1), (x2, y2), (0, 255, 0), 3) + img = process_lcd_with_p(edges, img) else: - lines = cv2.HoughLines(edges, 1, np.pi / 2, 118) - for i_line in lines: - for line in i_line: - rho = line[0] - theta = line[1] - if (theta < (np.pi / 4.)) or (theta > (3. * np.pi / 4.0)): # 垂直直线 - pt1 = (int(rho / np.cos(theta)), 0) - pt2 = (int((rho - img.shape[0] * np.sin(theta)) / np.cos(theta)), img.shape[0]) - cv2.line(img, pt1, pt2, (0, 0, 255)) - else: - pt1 = (0, int(rho / np.sin(theta))) - pt2 = (img.shape[1], int((rho - img.shape[1] * np.cos(theta)) / np.sin(theta))) - cv2.line(img, pt1, pt2, (0, 0, 255), 1) - filename = getImageName() + DEFAULT_FORMAT - cv2.imwrite(PREFIX + filename, img) - return HttpResponse(filename) - return HttpResponse('请使用POST方法') - - -def ideal_low_filter(img, D0): - """ - 生成一个理想低通滤波器(并返回) - """ - h, w = img.shape[:2] - filter_img = np.ones((h, w)) - u = np.fix(h / 2) - v = np.fix(w / 2) - for i in range(h): - for j in range(w): - d = np.sqrt((i - u) ** 2 + (j - v) ** 2) - filter_img[i, j] = 0 if d > D0 else 1 - return filter_img - - -def ideal_high_pass_filter(img, D0): - h, w = img.shape[:2] - filter_img = np.zeros((h, w)) - u = np.fix(h / 2) - v = np.fix(w / 2) - for i in range(h): - for j in range(w): - d = np.sqrt((i - u) ** 2 + (j - v) ** 2) - filter_img[i, j] = 0 if d < D0 else 1 - return filter_img - - -def butterworth_low_filter(img, D0, rank): - """ - 生成一个Butterworth低通滤波器(并返回) - """ - h, w = img.shape[:2] - filter_img = np.zeros((h, w)) - u = np.fix(h / 2) - v = np.fix(w / 2) - for i in range(h): - for j in range(w): - d = np.sqrt((i - u) ** 2 + (j - v) ** 2) - filter_img[i, j] = 1 / (1 + ((d / D0) ** (2 * rank))) - return filter_img - - -def butterworth_high_pass_filter(img, D0, rank): - """ - 生成一个Butterworth低通滤波器(并返回) - """ - h, w = img.shape[:2] - filter_img = np.zeros((h, w)) - u = np.fix(h / 2) - v = np.fix(w / 2) - for i in range(h): - for j in range(w): - d = np.sqrt((i - u) ** 2 + (j - v) ** 2) - filter_img[i, j] = 1 / (1 + ((D0 / d) ** (2 * rank))) - return filter_img - - -def gauss_low_pass_filter(img, d0): - """ - 生成一个指数低通滤波器(并返回) - """ - h, w = img.shape[:2] - filter_img = np.zeros((h, w)) - u = np.fix(h / 2) - v = np.fix(w / 2) - for i in range(h): - for j in range(w): - d = np.sqrt((i - u) ** 2 + (j - v) ** 2) - filter_img[i, j] = np.exp(-0.5 * (d ** 2) / (d0 ** 2)) - return filter_img - - -def gauss_high_pass_filter(img, d0): - """ - 生成一个指数低通滤波器(并返回) - """ - h, w = img.shape[:2] - filter_img = np.zeros((h, w)) - u = np.fix(h / 2) - v = np.fix(w / 2) - for i in range(h): - for j in range(w): - d = np.sqrt((i - u) ** 2 + (j - v) ** 2) - filter_img[i, j] = 1 - np.exp(-0.5 * (d ** 2) / (d0 ** 2)) - return filter_img - - -def filter_use_smooth(img, filter): - """ - 将图像img与滤波器filter结合,生成对应的滤波图像 - """ - # 首先进行傅里叶变换 - f = np.fft.fft2(img) - f_center = np.fft.fftshift(f) - # 应用滤波器进行反变换 - S = np.multiply(f_center, filter) # 频率相乘——l(u,v)*H(u,v) - f_origin = np.fft.ifftshift(S) # 将低频移动到原来的位置 - f_origin = np.fft.ifft2(f_origin) # 使用ifft2进行傅里叶的逆变换 - f_origin = np.abs(f_origin) # 设置区间 - return f_origin - - -def filter_use_sharpen(img, filter): - f = np.fft.fft2(img) - f_center = np.fft.fftshift(f) - # 应用滤波器进行反变换 - S = np.multiply(f_center, filter) # 频率相乘——l(u,v)*H(u,v) - f_origin = np.fft.ifftshift(S) # 将低频移动到原来的位置 - f_origin = np.fft.ifft2(f_origin) # 使用ifft2进行傅里叶的逆变换 - f_origin = np.abs(f_origin) # 设置区间 - f_origin = f_origin / np.max(f_origin.all()) - return f_origin + img = process_lcd_without_p(edges, img) + return HttpResponse(save_image(img)) + return HttpResponse('Please use POST') @csrf_exempt @@ -719,63 +294,26 @@ def smooth(request): img = cv2.imread(PREFIX + image, 0) # frequency domain fd = para['fd'] - filter = para['filter'] + my_filter = para['filter'] if fd: - if filter == 'ideal_low_pass_filter': + if my_filter == 'ideal_low_pass_filter': d0 = para.get('d0', 20) img = filter_use_smooth(img, ideal_low_filter(img, d0)) - elif filter == 'butterworth_low_pass_filter': + elif my_filter == 'butterworth_low_pass_filter': d0 = para.get('d0', 20) rank = para.get('rank', 2) - img = filter_use_smooth(img, butterworth_low_filter(img, d0, rank)) - elif filter == 'gauss_low_pass_filter': + img = filter_use_smooth(img, butterworth_low_pass_filter(img, d0, rank)) + elif my_filter == 'gauss_low_pass_filter': d0 = para.get('d0', 20) img = filter_use_smooth(img, gauss_low_pass_filter(img, d0)) else: size = para['size'] - if filter == 'average': + if my_filter == 'average': img = cv2.blur(img, (size, size)) - elif filter == 'median': + elif my_filter == 'median': img = cv2.medianBlur(img, size) - filename = getImageName() + DEFAULT_FORMAT - cv2.imwrite(PREFIX + filename, img) - return HttpResponse(filename) - return HttpResponse('请使用POST方法') - - -def process_roberts(img): - kernelx = np.array([[-1, 0], [0, 1]], dtype=int) - kernely = np.array([[0, -1], [1, 0]], dtype=int) - x = cv2.filter2D(img, cv2.CV_16S, kernelx) - y = cv2.filter2D(img, cv2.CV_16S, kernely) - # 转uint8 - absX = cv2.convertScaleAbs(x) - absY = cv2.convertScaleAbs(y) - return cv2.addWeighted(absX, 0.5, absY, 0.5, 0) - - -def process_sobel(img): - x = cv2.Sobel(img, cv2.CV_16S, 1, 0) # 对x求一阶导 - y = cv2.Sobel(img, cv2.CV_16S, 0, 1) # 对y求一阶导 - absX = cv2.convertScaleAbs(x) - absY = cv2.convertScaleAbs(y) - return cv2.addWeighted(absX, 0.5, absY, 0.5, 0) - - -def process_prewitt(img): - kernelx = np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]], dtype=int) - kernely = np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]], dtype=int) - x = cv2.filter2D(img, cv2.CV_16S, kernelx) - y = cv2.filter2D(img, cv2.CV_16S, kernely) - # 转uint8 - absX = cv2.convertScaleAbs(x) - absY = cv2.convertScaleAbs(y) - return cv2.addWeighted(absX, 0.5, absY, 0.5, 0) - - -def process_laplacian(img): - dst = cv2.Laplacian(img, cv2.CV_16S, ksize=3) - return cv2.convertScaleAbs(dst) + return HttpResponse(save_image(img)) + return HttpResponse('Please use POST') @csrf_exempt @@ -786,31 +324,29 @@ def sharpen(request): img = cv2.imread(PREFIX + image, 0) # frequency domain fd = para['fd'] - filter = para['filter'] + my_filter = para['filter'] if fd: - if filter == 'ideal_high_pass_filter': + if my_filter == 'ideal_high_pass_filter': d0 = para.get('d0', 40) img = filter_use_sharpen(img, ideal_high_pass_filter(img, d0)) - elif filter == 'butterworth_high_pass_filter': + elif my_filter == 'butterworth_high_pass_filter': d0 = para.get('d0', 20) rank = para.get('rank', 2) img = filter_use_sharpen(img, butterworth_high_pass_filter(img, d0, rank)) - elif filter == 'gauss_high_pass_filter': + elif my_filter == 'gauss_high_pass_filter': d0 = para.get('d0', 20) img = filter_use_sharpen(img, gauss_high_pass_filter(img, d0)) else: - if filter == 'Roberts': + if my_filter == 'Roberts': img = process_roberts(img) - elif filter == 'Sobel': + elif my_filter == 'Sobel': img = process_sobel(img) - elif filter == 'Prewitt': + elif my_filter == 'Prewitt': img = process_prewitt(img) - elif filter == 'Laplacian': + elif my_filter == 'Laplacian': img = process_laplacian(img) - filename = getImageName() + DEFAULT_FORMAT - cv2.imwrite(PREFIX + filename, img) - return HttpResponse(filename) - return HttpResponse('请使用POST方法') + return HttpResponse(save_image(img)) + return HttpResponse('Please use POST') @csrf_exempt @@ -830,10 +366,8 @@ def morphology(request): img = cv2.erode(img, kernel) elif op == 'dilate': img = cv2.dilate(img, kernel) - filename = getImageName() + DEFAULT_FORMAT - cv2.imwrite(PREFIX + filename, img) - return HttpResponse(filename) - return HttpResponse('请使用POST方法') + return HttpResponse(save_image(img)) + return HttpResponse('Please use POST') @csrf_exempt @@ -844,170 +378,11 @@ def noise(request): img = cv2.imread(PREFIX + image) op = para['type'] if op == 'gauss': - img = np.array(img / 255, dtype=float) - noise = np.random.normal(0, 0.1, img.shape) - img = img + noise - img = np.clip(img, 0.0, 1.0) - img = np.uint8(img * 255) + img = process_gauss_noise(img) elif op == 'salt_and_pepper': - range_salt = para.get('salt', 0.2) - range_peper = para.get('peper', 0.8) - output = np.zeros(img.shape, np.uint8) - for i in range(img.shape[0]): - for j in range(img.shape[1]): - rdn = random.random() - if rdn < range_salt: - output[i][j] = 0 - elif rdn > range_peper: - output[i][j] = 255 - else: - output[i][j] = img[i][j] - img = output - filename = getImageName() + DEFAULT_FORMAT - cv2.imwrite(PREFIX + filename, img) - return HttpResponse(filename) - return HttpResponse('请使用POST方法') - - -def process_geometric_mean(img): - output = np.zeros(img.shape, np.uint8) - for i in range(img.shape[0]): - for j in range(img.shape[1]): - ji = 1.0 - for m in range(-1, 2): - if 0 <= j + m < img.shape[1]: - ji *= img[i][j + m] - output[i][j] = math.pow(ji, 1 / 3) - return output - - -def process_arithmetic_mean(img): - output = np.zeros(img.shape, np.uint8) - for i in range(img.shape[0]): - for j in range(img.shape[1]): - sum = 0 - for m in range(-1, 2): - for n in range(-1, 2): - if 0 <= i + m < img.shape[0] and 0 <= j + n < img.shape[1]: - sum += img[i + m][j + n] - output[i][j] = int(sum / 9) - return output - - -def process_harmonic_filter(img): - output = np.zeros(img.shape, np.uint8) - for i in range(img.shape[0]): - for j in range(img.shape[1]): - sum = 0 - for m in range(-1, 2): - for n in range(-1, 2): - if 0 <= i + m < img.shape[0] and 0 <= j + n < img.shape[1]: - sum += 1 / img[i + m][j + n] - output[i][j] = int(9 / sum) - return output - - -def get_middle(array): - # 列表的长度 - length = len(array) - # 对列表进行选择排序,获得有序的列表 - for i in range(length): - for j in range(i + 1, length): - # 选择最大的值 - if array[j] > array[i]: - # 交换位置 - temp = array[j] - array[j] = array[i] - array[i] = temp - return array[int(length / 2)] - - -def process_max_sort(img): - output = np.zeros(img.shape, np.uint8) - array = [] - for i in range(img.shape[0]): - for j in range(img.shape[1]): - array.clear() - for m in range(-1, 2): - for n in range(-1, 2): - if 0 <= i + m < img.shape[0] and 0 <= j + n < img.shape[1]: - array.append(img[i + m][j + n]) - array.sort(reverse=True) - output[i][j] = max(array[0], img[i][j]) - return output - - -def process_min_sort(img): - output = np.zeros(img.shape, np.uint8) - array = [] - for i in range(img.shape[0]): - for j in range(img.shape[1]): - array.clear() - for m in range(-1, 2): - for n in range(-1, 2): - if 0 <= i + m < img.shape[0] and 0 <= j + n < img.shape[1]: - array.append(img[i + m][j + n]) - array.sort() - output[i][j] = min(array[0], img[i][j]) - return output - - -def process_median_sort(img): - output = np.zeros(img.shape, np.uint8) - array = [] - for i in range(img.shape[0]): - for j in range(img.shape[1]): - array.clear() - for m in range(-1, 2): - for n in range(-1, 2): - if 0 <= i + m < img.shape[0] and 0 <= j + n < img.shape[1]: - array.append(img[i + m][j + n]) - output[i][j] = get_middle(array) - return output - - -def process_high_choice(img, limit): - output = np.zeros(img.shape, np.uint8) - for i in range(img.shape[0]): - for j in range(img.shape[1]): - if img[i][j] > limit: - output[i][j] = img[i][j] - else: - output[i][j] = 0 - return output - - -def process_low_choice(img, limit): - output = np.zeros(img.shape, np.uint8) - for i in range(img.shape[0]): - for j in range(img.shape[1]): - if img[i][j] < limit: - output[i][j] = img[i][j] - else: - output[i][j] = 0 - return output - - -def process_pass_choice(img, min, max): - output = np.zeros(img.shape, np.uint8) - for i in range(img.shape[0]): - for j in range(img.shape[1]): - if min < img[i][j] < max: - output[i][j] = img[i][j] - else: - output[i][j] = 255 - return output - - -def process_stop_choice(img, min, max): - output = np.zeros(img.shape, np.uint8) - for i in range(img.shape[0]): - for j in range(img.shape[1]): - if min < img[i][j] < max: - output[i][j] = 0 - else: - output[i][j] = img[i][j] - return output + img = process_salt_and_peper_noise(img, para) + return HttpResponse(save_image(img)) + return HttpResponse('Please use POST') @csrf_exempt @@ -1047,10 +422,8 @@ def filtration(request): min_r = para.get('min', 20) max_r = para.get('max', 200) img = process_stop_choice(img, min_r, max_r) - filename = getImageName() + DEFAULT_FORMAT - cv2.imwrite(PREFIX + filename, img) - return HttpResponse(filename) - return HttpResponse('请使用POST方法') + return HttpResponse(save_image(img)) + return HttpResponse('Please use POST') @csrf_exempt @@ -1061,26 +434,17 @@ def wavelet(request): img = cv2.imread(PREFIX + image, 0) # 对img进行haar小波变换: cA, (cH, cV, cD) = dwt2(img, 'haar') - # 小波变换之后,低频分量对应的图像: - low_name = getImageName() + DEFAULT_FORMAT - cv2.imwrite(PREFIX + low_name, np.uint8(cA / np.max(cA) * 255)) - # 小波变换之后,水平方向高频分量对应的图像: - horizontal_high_name = getImageName() + DEFAULT_FORMAT - cv2.imwrite(PREFIX + horizontal_high_name, np.uint8(cH / np.max(cH) * 255)) - # 小波变换之后,垂直平方向高频分量对应的图像: - vertical_high_name = getImageName() + DEFAULT_FORMAT - cv2.imwrite(PREFIX + vertical_high_name, np.uint8(cV / np.max(cV) * 255)) - # 小波变换之后,对角线方向高频分量对应的图像: - diagonal_high_name = getImageName() + DEFAULT_FORMAT - cv2.imwrite(PREFIX + diagonal_high_name, np.uint8(cD / np.max(cD) * 255)) - # 根据小波系数重构回去的图像 rimg = idwt2((cA, (cH, cV, cD)), 'haar') - refactor_name = getImageName() + DEFAULT_FORMAT - cv2.imwrite(PREFIX + refactor_name, np.uint8(rimg)) - ret = [{"low": low_name, "horizontal_high": horizontal_high_name, "vertical_high": vertical_high_name, - "diagonal_high": diagonal_high_name, "refactor": refactor_name}] + ret = [ + {"low": save_image(np.uint8(cA / np.max(cA) * 255)), + "horizontal_high": save_image(np.uint8(cH / np.max(cH) * 255)), + "vertical_high": save_image(np.uint8(cV / np.max(cV) * 255)), + "diagonal_high": save_image(np.uint8(cD / np.max(cD) * 255)), + "refactor": save_image(np.uint8(rimg)) + } + ] return HttpResponse(ret) - return HttpResponse('请使用POST方法') + return HttpResponse('Please use POST') @csrf_exempt @@ -1097,14 +461,10 @@ def fourier(request): ishift = np.fft.ifftshift(f) iimg = np.fft.ifft2(ishift) iimg = np.abs(iimg) - fourier_transform_name = getImageName() + DEFAULT_FORMAT - inverse_name = getImageName() + DEFAULT_FORMAT - cv2.imwrite(PREFIX + fourier_transform_name, magnitude_spectrum) - cv2.imwrite(PREFIX + inverse_name, iimg) - ret = [{"fourier_transform": fourier_transform_name, "inverse": inverse_name}] + ret = [{"fourier_transform": save_image(magnitude_spectrum), "inverse": save_image(iimg)}] return HttpResponse(ret) - return HttpResponse('请使用POST方法') + return HttpResponse('Please use POST') -def r(request): +def load(request): return render(request, 'upload.html')