File size: 11,407 Bytes
4baf7bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
import io

import cv2
import numpy as np
import requests
from PIL import Image

"""
1、测试lama-cleaner的inpaint api
"""
def test_inpaint_api():
    """
    参数为image、mask
    :return:
    """

    # 加载原始图像并将其转换为灰度图像



    img_path = '/resources/jeyoo-img/img.png'
    mask_img_path = '/resources/jeyoo-img/img_mask.png'
    clean_img_path = "/resources/jeyoo-img/img_clean.png"

    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    cv2.imshow('gray', gray)

    cv2.imwrite(mask_img_path,gray)

    # image_file_object = cv2.imread(img_path)
    # mask_file_object =  cv2.imread(mask_img_path)

    r = requests.post('http://127.0.0.1:7860/inpaint',
                      files={
                          'image': open(img_path, 'rb'),
                          'mask': open(mask_img_path, 'rb')},
                      data={
                          'ldmSteps': 25,
                          'ldmSampler': "plms",
                          'zitsWireframe': bool(True),
                          'hdStrategy': "Crop",
                          'hdStrategyCropMargin': 196,
                          'hdStrategyCropTrigerSize': 800,
                          'hdStrategyResizeLimit': 2048,
                          'prompt': "",
                          'negativePrompt': "",
                          'croperX': 58,
                          'croperY': -26,
                          'croperHeight': 512,
                          'croperWidth': 512,
                          'useCroper': bool(False),
                          'sdMaskBlur': 5,
                          'sdStrength': 0.75,
                          'sdSteps': 50,
                          'sdGuidanceScale': 7.5,
                          'sdSampler': "pndm",
                          'sdSeed': -1,
                          'sdMatchHistograms': bool(False),
                          'sdScale': 1,
                          'cv2Radius': 5,
                          'cv2Flag': "INPAINT_NS",
                          'paintByExampleSteps': 50,
                          'paintByExampleGuidanceScale': 7.5,
                          'paintByExampleSeed': -1,
                          'paintByExampleMaskBlur': 5,
                          'paintByExampleMatchHistograms': bool(False),
                          'p2pSteps': 50,
                          'p2pImageGuidanceScale': 1.5,
                          'p2pGuidanceScale': 7.5,
                          'sizeLimit': 628
                      },
                      headers={'x-api-key': 'xxxx'}
                      )
    if (r.ok):
        # r.content contains the bytes of the returned image
        print(r)
        image_data = r.content

        # 将图片数据转换为图像对象
        image = Image.open(io.BytesIO(image_data))
        # 将图像对象保存到本地文件
        image.save(clean_img_path)
    else:
        r.raise_for_status()




"""
2、测试从从image根据 watermark 获取 mask img
"""
def test_get_mask_by_gradient():
    """
    在这个示例代码中,我们首先读取一张图片,并将其转换为灰度图像。
    然后,我们使用Sobel算子计算图像的梯度,并计算像素变化的平均值。
    接着,我们将像素变化小于平均值一半的像素设置为0,得到一个二值掩码。
    最后,我们使用findContours函数找到掩码中的轮廓,并使用boundingRect函数获取每个轮廓的矩形框。
    最后,我们在原图上绘制矩形框,并显示结果。
    """
    # 读取图片
    img = cv2.imread('../lama_cleaner_source_code/resources/jeyoo-img/image31.png')

    # 转换为灰度图像
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # 计算梯度

    # src:gray图像
    # ddepth:int类型的ddepth,输出图像的深度,若src.depth() = CV_32F, 取ddepth =-1/CV_32F/CV_64F
    # dx、dy:X、y方向的差分阶数
    grad_x = cv2.Sobel(gray, cv2.CV_32F, 1, 0)
    grad_y = cv2.Sobel(gray, cv2.CV_32F, 0, 1)
    # print("grad_x:{},grad_y:{}".format(grad_x,grad_y))

    # gray_x、gray_y是矩阵,第二个参数是权重
    grad = cv2.addWeighted(grad_x, 0.5, grad_y, 0.5, 0)

    # 计算像素变化小的区域

    # 对数组中的每一个元素求其绝对值。
    grad_abs = np.absolute(grad)
    # 相似变化的平均值
    grad_mean = np.mean(grad_abs)
    # 0.7是最大
    grad_threshold = grad_mean * 0.5
    grad_mask = grad_abs < grad_threshold
    # for i, element in enumerate(grad_abs):
    #     print("第 {} 行 ".format(i))
    #     for j in enumerate(element):
    #         print("{}".format(j))

    print("grad_mean:{},grad_threshold:{}".format(grad_mean,grad_threshold)) # grad_mean:93.4161148071289,grad_threshold:46.70805740356445


    # 获取像素变化小的区域的矩形框
    contours, hierarchy = cv2.findContours(grad_mask.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    # print(contours)
    rects = [cv2.boundingRect(cnt) for cnt in contours]

    # 在原图上绘制矩形框
    for rect in rects:
        cv2.rectangle(img, (rect[0], rect[1]), (rect[0] + rect[2], rect[1] + rect[3]), (0, 0, 255), 2)


    # 显示结果
    cv2.imshow('image', img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    cv2.imwrite('../lama_cleaner_source_code/resources/jeyoo-img/out/imgage31.png',img)


def test_get_mask_by_watermark():
    """
    从image根据 watermark_img 获取mask img

    要从图像中获取水印位置的掩码图像,您可以使用OpenCV中的模板匹配技术。模板匹配是一种在图像中查找给定模板的技术,它可以用于检测图像中的水印位置。
    以下是使用OpenCV从图像中获取水印位置的掩码图像的步骤:
    加载原始图像和水印图像。
    将水印图像转换为灰度图像。
    使用OpenCV中的模板匹配函数(cv2.matchTemplate)在原始图像中查找水印图像的位置。
    根据匹配结果创建掩码图像。在掩码图像中,将匹配位置设置为白色,其他位置设置为黑色。
    :return:
    """

    # 加载原始图像和水印图像
    img = cv2.imread('original_image.jpg')
    watermark = cv2.imread('watermark_image.jpg')

    # 将水印图像转换为灰度图像
    watermark_gray = cv2.cvtColor(watermark, cv2.COLOR_BGR2GRAY)

    # 使用模板匹配在原始图像中查找水印图像的位置
    result = cv2.matchTemplate(img, watermark_gray, cv2.TM_CCOEFF_NORMED)

    # 根据匹配结果创建掩码图像
    threshold = 0.8
    mask = np.zeros_like(result)
    mask[result >= threshold] = 255

    # 显示掩码图像
    cv2.imshow('Mask', mask)

    # 等待用户按下任意键
    cv2.waitKey(0)

    # 释放窗口
    cv2.destroyAllWindows()


def test_get_mask_by_watermark2():

    """
    在上面的代码中,我们使用Canny算子对灰度图像进行边缘检测,并使用cv2.findContours函数对边缘图像进行轮廓检测。
    然后,我们对每个轮廓进行形状分析,并根据筛选出的轮廓创建掩码图像。
    在筛选轮廓时,我们使用了cv2.isContourConvex函数来排除非凸形状的轮廓。您可以根据需要调整形状分析的参数来获得更好的结果。
    :return:
    """
    # 加载原始图像并将其转换为灰度图像
    img = cv2.imread('../lama_cleaner_source_code/resources/jeyoo-img/img.png')
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    cv2.imshow('gray', gray)
    cv2.waitKey(0)

    # 对灰度图像进行边缘检测
    edges = cv2.Canny(gray, 50, 150)
    cv2.imshow('edges', edges)
    cv2.waitKey(0)


    # 对边缘图像进行轮廓检测
    contours, hierarchy = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)


    # 对每个轮廓进行形状分析,筛选出可能是水印的轮廓
    watermark_contours = []
    for contour in contours:
        perimeter = cv2.arcLength(contour, True)
        approx = cv2.approxPolyDP(contour, 0.02 * perimeter, True)
        print(len(approx))
        if len(approx) == 6 and cv2.isContourConvex(approx):
            watermark_contours.append(approx)

    # 根据筛选出的轮廓,创建掩码图像
    mask = np.zeros_like(gray)
    for contour in watermark_contours:
        cv2.drawContours(mask, [contour], 0, 255, -1)

    # 显示掩码图像
    cv2.imshow('Mask', mask)

    # 等待用户按下任意键
    cv2.waitKey(0)

    # 释放窗口
    cv2.destroyAllWindows()


def test_get_mask_img_watermark3():
    """

    要为水印区域生成掩码图像,您可以使用OpenCV中的矩形掩码。以下是生成掩码图像的步骤:
    创建一个与原始图像大小相同的黑色图像,作为掩码图像。
    使用OpenCV中的 cv2.rectangle() 函数在掩码图像上绘制一个矩形,该矩形覆盖水印区域。
    将掩码图像转换为灰度图像,并使用OpenCV中的 cv2.threshold() 函数将其二值化,以便将水印区域设置为白色,其余区域设置为黑色。
    :return:
    """
    img = cv2.imread('../lama_cleaner_source_code/resources/jeyoo-img/img.png')

    # 创建掩码图像
    mask = np.zeros_like(img)

    # 定义水印区域
    x, y, w, h = 3, 18, 29, 29

    # 在掩码图像上绘制矩形
    cv2.rectangle(mask, (x, y), (x + w, y + h), (255, 255, 255), -1)

    # 将掩码图像转换为灰度图像
    mask_gray = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)

    # 将掩码图像二值化
    _, mask_binary = cv2.threshold(mask_gray, 1, 255, cv2.THRESH_BINARY)

    # 显示掩码图像
    cv2.imshow('Mask', mask_binary)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


"""
3、测试从image根据 watermark 获取 mask img
"""

def test_get_mask_by_inrange():

    """
    方式1
    :return:
    """
    img_path = '../lama_cleaner_docker/resources/jeyoo2-shuiyin.png'
    img = cv2.imread(img_path)
    # 转换为灰度图像
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # 计算掩码,删除像素位于该区间的
    mask = cv2.inRange(gray, 240, 255)
    cv2.imshow('mask1', mask)
    cv2.waitKey(0)


    """
    方式2
    """
    # 读取图片
    img = cv2.imread(img_path)
    cv2.imshow("img" ,img)
    cv2.waitKey(0)
    # 将图片转换为HSV颜色空间
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    cv2.imshow("hsv", hsv)
    cv2.waitKey(0)

    means, dev = cv2.meanStdDev(img)
    print("means:{}".format(means))
    # means: [[227.75111119]
    #         [228.73636804]
    #         [225.89541678]]

    # 定义颜色范围
    lower_color = np.array([100, 100, 100])
    upper_color = np.array([255, 255, 255])

    # 创建掩码
    mask2 = cv2.inRange(hsv, lower_color, upper_color)

    cv2.imshow("mask2", mask2)
    cv2.waitKey(0)

    # 获取选定区域
    result = cv2.bitwise_and(img, img, mask=mask)

    # 显示结果
    cv2.imshow('image', result)
    cv2.waitKey(0)
    cv2.destroyAllWindows()



"""
测试opencv的inpaint修复方法
"""
def test_repire_old_img_by_cv():
    img = cv2.imread('../lama_cleaner_source_code/resources/jeyoo-shuiyin.png')
    mask = cv2.imread('../lama_cleaner_source_code/resources/jeyoo2-shuiyin_mask.jpg', cv2.IMREAD_GRAYSCALE)
    dst = cv2.inpaint(img, mask, 3, cv2.INPAINT_TELEA)
    cv2.imshow('dst', dst)
    cv2.waitKey(0)
    cv2.destroyAllWindows()