Skip to content

Commit

Permalink
1.3.6
Browse files Browse the repository at this point in the history
  • Loading branch information
赵文文 committed Oct 15, 2020
1 parent d8125dc commit 892cc69
Show file tree
Hide file tree
Showing 77 changed files with 689 additions and 1,949 deletions.
16 changes: 16 additions & 0 deletions .idea/codeStyles/Project.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions .idea/gradle.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

123 changes: 54 additions & 69 deletions OpenNSFW/src/main/java/com/zwy/opennsfw/core/Classifier.kt
Original file line number Diff line number Diff line change
Expand Up @@ -112,17 +112,13 @@ class Classifier private constructor(config: Config) {
}
}

//"/data/user/0/com.zwy.demo/files/nsfw.tflite"
init {

// val file = File(
// config.nsfwModuleFilePath
// ?: throw java.lang.NullPointerException("未配置模型路径,请调用Classifier.Build().nsfwModuleFilePath(模型路径)初始化")
// )
// if (!file.exists()) throw NullPointerException("模型加载失败,请确认路径是否正确")
try {
tflite =
Interpreter(loadModelFile(context = config.context!!), getTfLiteOptions(config.isOpenGPU))
Interpreter(
loadModelFile(context = config.context!!),
getTfLiteOptions(config.isOpenGPU)
)
if (config.isOpenGPU) "开启GPU加速成功".d()
} catch (e: Exception) {
"不支持GPU加速".e()
Expand Down Expand Up @@ -160,33 +156,25 @@ class Classifier private constructor(config: Config) {


private fun convertBitmapToByteBuffer(bitmap_: Bitmap) {
imgData.rewind()
val W = bitmap_.width
val H = bitmap_.height

val w_off = max((W - INPUT_WIDTH) / 2, 0)
val h_off = max((H - INPUT_HEIGHT) / 2, 0)

//把每个像素的颜色值转为int 存入intValues
bitmap_.getPixels(intValues, 0, INPUT_WIDTH, h_off, w_off, INPUT_WIDTH, INPUT_HEIGHT)

val startTime = SystemClock.uptimeMillis()

for (color in intValues) {
val r1 = Color.red(color)
val g1 = Color.green(color)
val b1 = Color.blue(color)

val rr1 = r1 - 123
val gg1 = g1 - 117
val bb1 = b1 - 104

imgData.putFloat(bb1.toFloat())
imgData.putFloat(gg1.toFloat())
imgData.putFloat(rr1.toFloat())
SystemClock.uptimeMillis().let { startTime ->
imgData.rewind()
//把每个像素的颜色值转为int 存入intValues
bitmap_.getPixels(
intValues,
0,
INPUT_WIDTH,
max((bitmap_.height - INPUT_HEIGHT) / 2, 0),
max((bitmap_.width - INPUT_WIDTH) / 2, 0),
INPUT_WIDTH,
INPUT_HEIGHT
)
for (color in intValues) {
imgData.putFloat((Color.blue(color) - 104).toFloat())
imgData.putFloat((Color.green(color) - 117).toFloat())
imgData.putFloat((Color.red(color) - 123).toFloat())
}
"数据装载成功,耗时:${(SystemClock.uptimeMillis() - startTime)} ms".d()
}
val endTime = SystemClock.uptimeMillis()
"数据装载成功,耗时:${(endTime - startTime)} ms".d()
}

// # 根据路径获取图片 Image.open(path)
Expand All @@ -203,41 +191,38 @@ class Classifier private constructor(config: Config) {
// # 删除所有单维度的条目
// # 输出扫描结果
fun run(bitmap: Bitmap): NsfwBean {
//缩放位图时是否应使用双线性过滤。如果这是正确的,则在缩放时将使用双线性滤波,从而以较差的性能为代价具有更好的图像质量。如果这是错误的,则使用最近邻居缩放,这将使图像质量较差但速度更快。推荐的默认设置是将滤镜设置为“ true”,因为双线性滤镜的成本通常很小,并且改善的图像质量非常重要
val stream = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream)
stream.close()
val bitmap_256 = Bitmap.createScaledBitmap(bitmap, 256, 256, true)

convertBitmapToByteBuffer(bitmap_256)
//
val startTime = SystemClock.uptimeMillis()
// out
val outArray = Array(1) { FloatArray(2) }

tflite.run(imgData, outArray)

val endTime = SystemClock.uptimeMillis()
val nsfw = NsfwBean(outArray[0][0], outArray[0][1])
"扫描完成[${nsfw}]耗时: ${(endTime - startTime)} ms".d()
return nsfw
}

fun bitmap2RGB(bitmap: Bitmap): ByteArray? {
val bytes = bitmap.byteCount //返回可用于储存此位图像素的最小字节数
val buffer =
ByteBuffer.allocate(bytes) // 使用allocate()静态方法创建字节缓冲区
bitmap.copyPixelsToBuffer(buffer) // 将位图的像素复制到指定的缓冲区
val rgba = buffer.array()
val pixels = ByteArray(rgba.size / 4 * 3)
val count = rgba.size / 4

//Bitmap像素点的色彩通道排列顺序是RGBA
for (i in 0 until count) {
pixels[i * 3] = rgba[i * 4] //R
pixels[i * 3 + 1] = rgba[i * 4 + 1] //G
pixels[i * 3 + 2] = rgba[i * 4 + 2] //B
SystemClock.uptimeMillis().let { startTime ->
//缩放位图时是否应使用双线性过滤。如果这是正确的,则在缩放时将使用双线性滤波,从而以较差的性能为代价具有更好的图像质量。如果这是错误的,则使用最近邻居缩放,这将使图像质量较差但速度更快。推荐的默认设置是将滤镜设置为“ true”,因为双线性滤镜的成本通常很小,并且改善的图像质量非常重要
ByteArrayOutputStream().let { stream ->
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream)
stream.close()
convertBitmapToByteBuffer(Bitmap.createScaledBitmap(bitmap, 256, 256, true))
// out
Array(1) { FloatArray(2) }.apply {
tflite.run(imgData, this)
val nsfw = NsfwBean(this[0][0], this[0][1])
"扫描完成[${nsfw}]耗时: ${(SystemClock.uptimeMillis() - startTime)} ms".d()
return nsfw
}
}
}
return pixels
}

// fun bitmap2RGB(bitmap: Bitmap): ByteArray? {
// val bytes = bitmap.byteCount //返回可用于储存此位图像素的最小字节数
// val buffer =
// ByteBuffer.allocate(bytes) // 使用allocate()静态方法创建字节缓冲区
// bitmap.copyPixelsToBuffer(buffer) // 将位图的像素复制到指定的缓冲区
// val rgba = buffer.array()
// val pixels = ByteArray(rgba.size / 4 * 3)
// val count = rgba.size / 4
//
// //Bitmap像素点的色彩通道排列顺序是RGBA
// for (i in 0 until count) {
// pixels[i * 3] = rgba[i * 4] //R
// pixels[i * 3 + 1] = rgba[i * 4 + 1] //G
// pixels[i * 3 + 2] = rgba[i * 4 + 2] //B
// }
// return pixels
// }
}
2 changes: 1 addition & 1 deletion OpenNSFW/src/main/java/com/zwy/opennsfw/utils/kt.kt
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ fun String.d() = Log.d(TAG, this)

fun String.e() = Log.e(TAG, this)

class NsfwBean(val sfw: Float, val nsfw: Float) {
open class NsfwBean(val sfw: Float, val nsfw: Float) {
override fun toString(): String {
val floatFormat = DecimalFormat("0.0000")
floatFormat.roundingMode = RoundingMode.HALF_UP
Expand Down
File renamed without changes.
49 changes: 49 additions & 0 deletions app/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
android {
compileSdkVersion 30
buildToolsVersion "30.0.2"

defaultConfig {
applicationId "com.zww.sample"
minSdkVersion 21
targetSdkVersion 30
versionCode 136
versionName "1.3.6"

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
debug {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}

aaptOptions {
noCompress "tflite"
}
}

dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.1'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
implementation project(path: ':initializer')
implementation project(path: ':nsfw')
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'

//权限
implementation 'com.yanzhenjie:permission:2.0.3'
}
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
<uses-permission android:name="android.permission.CAMERA" />

<application
android:name=".BaseApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
Expand All @@ -18,17 +17,13 @@
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
</activity>

<activity
android:name=".ui.SplashActivity"
android:screenOrientation="portrait"
android:theme="@style/Splash">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

</application>

</manifest>
File renamed without changes
File renamed without changes
Binary file added app/src/main/assets/nsfw.tflite
Binary file not shown.
27 changes: 27 additions & 0 deletions app/src/main/java/com/zww/sample/MainActivity.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.zww.sample

import android.graphics.BitmapFactory
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.zwy.nsfw.getNSFWScore
import java.util.*

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

resources.assets.also { asset ->
asset.list("img")?.forEach {
"img/$it".also { assetFilePath ->
val startTime = Date().time
BitmapFactory.decodeStream(asset.open(assetFilePath)).also {
it.getNSFWScore()
it.recycle()
}
}
}
}
}
}
File renamed without changes
6 changes: 6 additions & 0 deletions app/src/main/res/layout/activity_main.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
File renamed without changes.
File renamed without changes.
File renamed without changes.
1 change: 1 addition & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ buildscript {
classpath 'com.android.tools.build:gradle:4.0.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'org.greenrobot:greendao-gradle-plugin:3.3.0'
classpath "guru.stefma.bintrayrelease:bintrayrelease:1.0.0"
}
}

Expand Down
1 change: 1 addition & 0 deletions initializer/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/build
53 changes: 53 additions & 0 deletions initializer/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: "guru.stefma.bintrayrelease"
android {
compileSdkVersion 30
buildToolsVersion "30.0.2"

defaultConfig {
minSdkVersion 21
targetSdkVersion 30
versionCode 136
versionName "1.3.6"

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
consumerProguardFiles "consumer-rules.pro"
}

buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}

dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.2'
implementation 'androidx.appcompat:appcompat:1.2.0'
api project(path: ':nsfw')
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'

}

version = "1.3.6"
group = "com.zwy.nsfw_initializer"
publish {
userOrg = 'devzwy'
repoName = 'maven'
artifactId = 'com.zwy.nsfw_initializer'
desc = 'android端离线鉴黄库快速初始化库'
website = 'https://github.com/devzwy'
}

tasks.withType(Javadoc) {//防止编码问题
options.addStringOption('Xdoclint:none', '-quiet')
options.addStringOption('encoding', 'UTF-8')
options.addStringOption('charSet', 'UTF-8')
}
Empty file added initializer/consumer-rules.pro
Empty file.
Loading

0 comments on commit 892cc69

Please sign in to comment.