* Adds each element of the image to its local neighbors, weighted by the kernel * @example * ```ts * import { Jimp } from "jimp"; * * const image = await Jimp.read("test/image.png"); * * image.convolute([ * [-1, -1, 0], * [-1, 1, 1], * [0, 1, 1], * ]); * ```
(image: I, options: ConvolutionOptions)
| 567 | * ``` |
| 568 | */ |
| 569 | convolution<I extends JimpClass>(image: I, options: ConvolutionOptions) { |
| 570 | const parsed = ConvolutionOptionsSchema.parse(options); |
| 571 | const { kernel, edgeHandling = Edge.EXTEND } = |
| 572 | "kernel" in parsed ? parsed : { kernel: parsed, edgeHandling: undefined }; |
| 573 | |
| 574 | if (!kernel[0]) { |
| 575 | throw new Error("kernel must be a matrix"); |
| 576 | } |
| 577 | |
| 578 | const newData = Buffer.from(image.bitmap.data); |
| 579 | const kRows = kernel.length; |
| 580 | const kCols = kernel[0].length; |
| 581 | const rowEnd = Math.floor(kRows / 2); |
| 582 | const colEnd = Math.floor(kCols / 2); |
| 583 | const rowIni = -rowEnd; |
| 584 | const colIni = -colEnd; |
| 585 | |
| 586 | let weight; |
| 587 | let rSum; |
| 588 | let gSum; |
| 589 | let bSum; |
| 590 | let ri; |
| 591 | let gi; |
| 592 | let bi; |
| 593 | let xi; |
| 594 | let yi; |
| 595 | let idxi; |
| 596 | |
| 597 | image.scan((x, y, idx) => { |
| 598 | bSum = 0; |
| 599 | gSum = 0; |
| 600 | rSum = 0; |
| 601 | |
| 602 | for (let row = rowIni; row <= rowEnd; row++) { |
| 603 | for (let col = colIni; col <= colEnd; col++) { |
| 604 | xi = x + col; |
| 605 | yi = y + row; |
| 606 | weight = kernel[row + rowEnd]![col + colEnd]!; |
| 607 | idxi = image.getPixelIndex(xi, yi, edgeHandling); |
| 608 | |
| 609 | if (idxi === -1) { |
| 610 | bi = 0; |
| 611 | gi = 0; |
| 612 | ri = 0; |
| 613 | } else { |
| 614 | ri = image.bitmap.data[idxi + 0]!; |
| 615 | gi = image.bitmap.data[idxi + 1]!; |
| 616 | bi = image.bitmap.data[idxi + 2]!; |
| 617 | } |
| 618 | |
| 619 | rSum += weight * ri; |
| 620 | gSum += weight * gi; |
| 621 | bSum += weight * bi; |
| 622 | } |
| 623 | } |
| 624 | |
| 625 | if (rSum < 0) { |
| 626 | rSum = 0; |
nothing calls this directly
no test coverage detected
searching dependent graphs…