ANTICHAT

ANTICHAT (https://forum.antichat.xyz/index.php)
-   Общие вопросы программирования (https://forum.antichat.xyz/forumdisplay.php?f=206)
-   -   Удаление фона с картинок (python) (https://forum.antichat.xyz/showthread.php?t=1406631)

chapo 01.11.2021 15:06

Привет, как удалить белый фон с 20000 картинок?

Этот код заменяет изображение на серый квадрат

Python:





Код:

from
PIL
import
Image
def
convertImage
(
)
:
img
=
Image
.
open
(
"./image.png"
)
img
=
img
.
convert
(
"RGBA"
)
datas
=
img
.
getdata
(
)
newData
=
[
]
for
items
in
datas
:
if
item
[
0
]
==
255
and
item
[
1
]
==
255
and
item
[
2
]
==
255
:
newData
.
append
(
(
255
,
255
,
255
,
0
)
)
else
:
newData
.
append
(
item
)
img
.
putdata
(
newData
)
img
.
save
(
"./New.png"
,
"PNG"
)
print
(
"Successful"
)
convertImage
(
)


copypaste_scripter 01.11.2021 18:43

не знаю как тебе будет полезно, но в фотошопе автоматом может делать такое вроде

chapo 01.11.2021 19:07

Нашел способ. Немного грузит систему, но работает более менее нормально

https://forum.antichat.xyz/attachmen...815cc70bf6.png

код:

Python:





Код:

import
cv2
import
numpy
as
np
import
imghdr
import
os
def
removeBackground
(
file
,
savePath
)
:
try
:
img
=
cv2
.
imread
(
file
)
gray
=
cv2
.
cvtColor
(
img
,
cv2
.
COLOR_BGR2GRAY
)
mask
=
cv2
.
threshold
(
gray
,
250
,
255
,
cv2
.
THRESH_BINARY
)
[
1
]
mask
=
255
-
mask
        kernel
=
np
.
ones
(
(
3
,
3
)
,
np
.
uint8
)
mask
=
cv2
.
morphologyEx
(
mask
,
cv2
.
MORPH_OPEN
,
kernel
)
mask
=
cv2
.
morphologyEx
(
mask
,
cv2
.
MORPH_CLOSE
,
kernel
)
mask
=
cv2
.
GaussianBlur
(
mask
,
(
0
,
0
)
,
sigmaX
=
2
,
sigmaY
=
2
,
borderType
=
cv2
.
BORDER_DEFAULT
)
mask
=
(
2
*
(
mask
.
astype
(
np
.
float32
)
)
-
255.0
)
.
clip
(
0
,
255
)
.
astype
(
np
.
uint8
)
result
=
img
.
copy
(
)
result
=
cv2
.
cvtColor
(
result
,
cv2
.
COLOR_BGR2BGRA
)
result
[
:
,
:
,
3
]
=
mask
        cv2
.
imwrite
(
savePath
,
result
)
cv2
.
waitKey
(
0
)
cv2
.
destroyAllWindows
(
)
except
:
open
(
savePath
,
'wb'
)
.
write
(
file
)
saveTo
=
'noBgImages'
for
i
in
range
(
1
,
17500
)
:
file
=
str
(
i
)
+
'.png'
if
os
.
path
.
isfile
(
file
)
:
if
imghdr
.
what
(
file
)
==
'png'
or
imghdr
.
what
(
file
)
==
'jpeg'
:
print
(
f'{i}: Removing bg from{file}, saving to{saveTo}\\{file}'
)
removeBackground
(
file
,
saveTo
+
'\\'
+
file
)
else
:
print
(
f'{i}[SKIP] NOT A PNG ({imghdr.what(file)}).{file}'
)



Время: 17:07