i am getting this error

2 views (last 30 days)
Rishith Reddy
Rishith Reddy on 24 Oct 2022
Answered: DGM on 24 Oct 2022
i=imread("Lena512.png")
i_i=im2double(i);
k=ones(4,4)/16;
b=1
conv2d(i_i,k,512)
function conv2d(i,k,b)
[m,n]= size(k);
[y,x]=size(i);
y=y-m+1;
x=x-m+1;
ni=zeros(y,x)
for l=2:1:y
for j=2:1:x
ni(l,j)=sum(i(l:l+m-1,j:j+n-1)*k)+b
end
end
end
Unable to perform assignment because the size of the left side is 1-by-1 and the size of the right side is 1-by-4.
ni(l,j)=sum(i(l:l+m-1,j:j+n-1)*k)+b
respective python code its working
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 24 21:29:27 2022
@author: rishi
"""
import numpy as np
import cv2
import os
os.chdir(r"C:\Users\rishi\Downloads")
image=cv2.imread("Lena512.png")
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
k=np.ones([4,4],dtype='int')/16
def convolution2d(image, kernel,bias):
m, n = kernel.shape
if (m == n):
y, x = image.shape
y = y - m + 1
x = x - m + 1
new_image = np.zeros((y,x))
for i in range(y):
for j in range(x):
new_image[i][j] = np.sum(image[i:i+m, j:j+m]*kernel) + bias
return new_image
x=convolution2d(image,k,bias=1)
cv2.imwrite('blurrey.jpg',x)

Answers (1)

DGM
DGM on 24 Oct 2022
Two things:
  • use elementwise multiplication between the sample and the filter kernel
  • sum() normally only takes the sum over the first non-singleton dimension. If you need the sum over more than one dimension, you'll have to do so in one way or another.
This is a start
inpict = imread('cameraman.tif');
inpict = im2double(inpict);
fk = ones(4,4)/16; % sum-normalized
b = 0; % offset?
outpict = conv2d(inpict,fk,b);
imshow(outpict)
function output = conv2d(thisimg,thisfk,offset)
[m,n] = size(thisfk);
[y,x] = size(thisimg);
y = y-m+1;
x = x-m+1;
output = zeros(y,x);
for l = 2:1:y
for j = 2:1:x
sample = thisimg(l:l+m-1,j:j+n-1);
output(l,j) = sum(sample.*thisfk,'all') + offset;
end
end
end
Depending on your goals, the window positioning and image padding may be issues of concern. See the related questions and answers.
general sliding/moving window filter base
same thing only with a gaussian mean setup
basic mean filter examples
basic convolution build (full size)
basic convolution build (same size)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!