我想的是把图片每2×4(2是底)为一块读取,然后提取出里面对比度最大的两个值
然后我用了 kmeans-plusplus ,但是这个库居然有语法错误(让gpt帮他修了)
然后我输入了这个:

这是他的输出:

这是我的代码
const Jimp = require('jimp');
const { Clusterer } = require('kmeans-plusplus');
async function lofiImage(imagePath, outputPath) {
try {
const image = await Jimp.read(imagePath);
let width = image.bitmap.width;
let height = image.bitmap.height;
// 填充白色像素,使尺寸可以被 2x4 整除
const paddingWidth = (2 - (width % 2)) % 2;
const paddingHeight = (4 - (height % 4)) % 4;
image.resize(width + paddingWidth, height + paddingHeight);
width += paddingWidth;
height += paddingHeight;
const blockSize = { width: 2, height: 4 };
const lofiData = [];
for (let y = 0; y < height; y += blockSize.height) {
for (let x = 0; x < width; x += blockSize.width) {
const block = [];
for (let j = y; j < y + blockSize.height; j++) {
for (let i = x; i < x + blockSize.width; i++) {
const color = Jimp.intToRGBA(image.getPixelColor(i, j));
block.push([color.r, color.g, color.b]);
}
}
console.log(block);
// KMeans 聚类
const clusterer = new Clusterer(block);
const kmeansResult = clusterer.clusterize(3);
const dominantColors = kmeansResult.centroids;
// 颜色简化
const reducedBlock = block.map(pixel => {
const distances = dominantColors.map(color => {
const diffR = pixel[0] - color[0];
const diffG = pixel[1] - color[1];
const diffB = pixel[2] - color[2];
return diffR * diffR + diffG * diffG + diffB * diffB;
});
const closestColorIndex = distances.indexOf(Math.min(...distances));
return dominantColors[closestColorIndex];
});
lofiData.push({ x, y, colors: dominantColors, reducedBlock });
}
}
// (你需要实现将 lofiData 转换为图片或其他格式的输出)
// 此处仅打印 dominantColors, 你需要根据需求编写图片生成部分
console.log(lofiData);
// 创建一个新的 Jimp 图片,并填充颜色
const outputImage = new Jimp(width, height, 0xFFFFFFFF); // 白色背景
for (const { x, y, reducedBlock } of lofiData) {
let k=0;
for (let j = y; j < y + blockSize.height; j++) {
for (let i = x; i < x + blockSize.width; i++) {
const color = reducedBlock[k];
outputImage.setPixelColor(Jimp.rgbaToInt(color[0], color[1], color[2], 255), i, j);
k++;
}
}
}
await outputImage.writeAsync(outputPath);
} catch (error) {
console.error('Error processing image:', error);
}
}
// 使用示例
lofiImage('input.png', 'output.png')
.catch(error => {
console.error("An error occurred:", error);
});
这是修复后的库文件(把后缀都改成 .js 然后覆盖 node_modules\kmeans-plusplus\dist )
对了jimp要装老版本的