import java.io.File
import javax.imageio.ImageIO
import java.awt.image.BufferedImage
val img = ImageIO.read(newFile("Filename.jpg"))
val w = img.getWidth
val h = img.getHeight
for (x <- 0 until w)
for (y <- 0 until h)
img.getRGB(x,y)
ImageIO.write(img,"jpg",new File("test.jpg"))
如何将img转换为字节数组,并计算其中的绿色像素。
发布于 2017-11-09 20:35:12
您可以通过比较每个像素的RGB值和绿色的RGB值来计算绿色像素的数量。示例:
...
val w = img.getWidth
val h = img.getHeight
val green = Color.GREEN
var ctrGreen = 0
var ctrTotal = 0
for (x <- 0 until w)
for (y <- 0 until h) {
val c = new Color(img.getRGB(x, y))
if (isEqual(c, green)) {
ctrGreen += 1
}
ctrTotal += 1;
}
println("Green pixel count: " + ctrGreen)
println("Total pixel count: " + ctrTotal)
}
def isEqual(c1: Color, c2: Color): Boolean = {
c1.getRed == c2.getRed && c1.getBlue == c2.getBlue && c1.getGreen == c2.getGreen
}
但有时很难找到与颜色的RGB值完全匹配的值(例如,在绿色的情况下,它是(0,255,0) )。因此,您还可以检查像素是否属于某个颜色范围。示例:
....
val lightGreen = new Color(0,255,0)
val darkGreen = new Color(0,100,0)
var ctrGreen = 0
var ctrTotal = 0
for (x <- 0 until w)
for (y <- 0 until h) {
val c = new Color(img.getRGB(x, y))
if (isBetween(c, lightGreen,darkGreen)) {
ctrGreen += 1
}
ctrTotal += 1;
}
println("Green pixel count: " + ctrGreen)
println("Total pixel count: " + ctrTotal)
}
def isBetween(c: Color, c1: Color, c2: Color): Boolean = {
c.getRed >= c1.getRed && c.getRed <= c2.getRed && c.getBlue >= c1.getBlue && c.getBlue <= c2.getBlue && c.getGreen <= c1.getGreen && c.getGreen >= c2.getGreen
}
https://stackoverflow.com/questions/47194335
复制相似问题